I am able to curl to node.js server but unable to http request from javascript

425 Views Asked by At

At this moment I am able to do curl -X GET 127.0.0.1:8081/flower in my command prompt and receive my JSON like I was expecting.

However, whenever I try to do the same GET request to the same exact URL from my code, I get undefined in every way I try. Below is my code for javascript and node.js. I would like to save the responseText to a global variable to be able to be saved as an array.

This is my HTTP request to pull the JSON request from the server:

function apiCall() {

 var menuRqst = new XMLHttpRequest;
    menuRqst.open('GET', 'http://127.0.0.1:8081/flower', true);
    menuRqst.send();
    menuRqst.addEventListener('readystatechange', processRequest, false);
    function processRequest(d) {
        if (menuRqst.readyState === 4 && menuRqst.status === 200) {
            var flowResponse = menuRqst.responseText;
            return flowResponse;
        }
    }
}

This is my node.js where I can curl -X GET 127.0.0.1:8081/flower and receive the data found in flower.JSON as a response:

var express = require('express');
var app = express();
var fs = require("fs");

app.get('/flower', function (req, res) {
    fs.readFile(__dirname + "/" + "flower.json", 'utf8', function (err, data) {
        console.log(data);
        res.end(data);
    });
})

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)
})
2

There are 2 best solutions below

3
diegoaguilar On

It's all about asynchrony. apiCall is not returning anything.

Also, what's more you should find a way to prepare the response when is ready, probably wrapping a Promise at the start of apiCall.

Also, if this is browser code, you may want to try out fetch and use async/await.

With fetch:

async function apiCall () {
  const response = await fetch('http://127.0.0.1:8081/flower');
  const jsonResponse = await response.json();
  return jsonResponse
}
1
Gloat On

I have done it, I think with help from cors and I also merged the cordova project into the node.js project. I was able to successfully achieve this with this code. Javascript:

    function httpGet(theUrl) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, false); // false for synchronous request
    xmlHttp.send(null);
    return xmlHttp.responseText;
}