Mr Spartacus
Mr Spartacus

Reputation: 127

AJAX call not receiving a response from webserver

I've looked at related questions and none have helped me. I am therefore creating this question.

So my client decrypts URLs and sends them to my server, which then decrypts them and makes an API call using the decrypted request. On the server side everything seems to be working fine. No errors are being thrown. Logs seem fine etc.

My AJAX looks like:

var handleRequest = function(request){
    $.ajax({
        type: "GET",
        url: host + '/requests?call=' + request,
        success: function(data) {
        var rawJSON = JSON.stringify(data, null, 2);
        console.log('Recieved: ' + rawJSON);
        editor.setValue(rawJSON);
       },
       error: function(jqXHR, responseText,status){
            console.log(jqXHR.responseText)
       },
       dataType: 'jsonp'
    });
}

Server side:

app.get('/requests', function(req, res) {
    var call = req.query.call;
    var decryptedRequest = decryptRequest(call);
    console.log("Recieved: " + decryptedRequest);

    var rawJson = retriever.makeExternalCall(decryptedRequest);
    console.log('Sending response to client');

    res.setHeader('Content-Type', 'application/json');
    res.send(rawJson);
});

Method used above:

var requestService = require('request');

module.exports = {
    makeExternalCall: function(url) {
        console.log('Making call to: ' + url);
        requestService(url, function(error, response, body){
            console.log(body);
            return body;
        });
    }
}

Strangely when I replace

res.send(rawJson);

with

res.send('hello');

I get a response. Any ideas on what is going on here?

Upvotes: 1

Views: 310

Answers (1)

bibek shrestha
bibek shrestha

Reputation: 448

The function makeExternalCall is an async function. Returning from callback doesn't work as the async function has already returned before returning the data and hence rawJson is undefined.

Solution to this is proper usage of the callback.

var requestService = require('request');

module.exports = {
    makeExternalCall: function(url,callback) {
        console.log('Making call to: ' + url);
        requestService(url, callback);
    }
}

And then in API handler

app.get('/requests', function(req, res) {
    var call = req.query.call;
    var decryptedRequest = decryptRequest(call);
    console.log("Recieved: " + decryptedRequest);

    retriever.makeExternalCall(decryptedRequest, function(error, response, body) {
        if (error) {
            res.send("error message");
        } else {
            res.setHeader('Content-Type', 'application/json');
            res.send(body);
        }
    })
});

Upvotes: 2

Related Questions