AJAX调用未收到来自网络服务器

时间:2017-01-27 21:02:49

标签: javascript ajax node.js

我查看过相关问题但没有人帮助过我。因此,我正在创建这个问题。

所以我的客户端解密URL并将它们发送到我的服务器,然后服务器解密它们并使用解密的请求进行API调用。在服务器端,一切似乎都运行正常。没有错误被抛出。日志似乎很好等。

我的AJAX看起来像:

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'
    });
}

服务器端:

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);
});

上面使用的方法:

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;
        });
    }
}

当我替换

时奇怪
res.send(rawJson);

res.send('hello');

我收到回复。关于这里发生了什么的任何想法?

1 个答案:

答案 0 :(得分:1)

函数 import java.util.Arrays; import java.util.Scanner; public class Polynomial { private int degree; private int [] coefficient; private double evaluation; private double sum; private double value; Scanner key = new Scanner(System.in); public Polynomial(int degree) { this.degree = degree; coefficient = new int [degree+1]; } public void setCoefficient(int coefficient) { this.coefficient[this.degree] = coefficient; } public int getCoefficient(int degree) { return coefficient[degree]; } public double Evaluate(double value) { this.value =value; for (int i=0; i<=degree; i++) { System.out.println("Enter coefficent for position " + i); this.coefficient[i] = key.nextInt(); evaluation = Math.pow(value, i)*this.coefficient[0] ; this.sum += evaluation; } return sum; } /** Standard toString method */ //needed something better than this below...needed an actual polynomial printed out public String toString() { return "The degree of the polynomial is " + degree + " and the value for which it has been evaluated is" + value; } } 是异步函数。从回调返回不起作用,因为异步函数在返回数据之前已经返回,因此makeExternalCall rawJson

解决这个问题的方法是正确使用回调。

is undefined

然后在API处理程序

var requestService = require('request');

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