我在客户端使用html,而服务器端代码在node.js上。我在nodejs应用程序中定义了一些URL,我从客户端html文件中调用它们。从节点,我正在另一台服务器上调用我的REST应用程序。该其余应用程序是使用Jersey Java Web服务编写的。我可以从html和节点代码中调用node.js,并且从Jersey Web服务模块获得响应。收到此响应后,我将其设置为node.js的响应对象,但此响应在html jquery ajax调用上不可用。

$.ajax({
    type :"POST",
    dataType: 'json',
    data: jsontest,
    url: 'http://<code>localhost</code>:9999/hello',
    success: function(data) {
        console.log('success');
        console.log(data);
        console.log(data.id);
    }, error : function(response) {
        console.log(JSON.stringify(response));
    }
});


服务器端代码:

var tmp = req;
var authentication = JSON.stringify(tmp.body.authenticationKey);

console.log("authentication :- "+authentication);

requestObj({
    url : "http://<code>restserver</code>:port/restmodule/controller/hello",
    method : "POST",
    headers : { "Content-Type" : "application/json","pubKey":authentication},
    body : JSON.stringify(tmp.body)
  },
  function (error, res, body) {
    indexresponseBody = JSON.stringify(JSON.parse(body).message);
  }
);

res.writeHead(200, {'content-type':'text/html'});

console.log("JSON returned from REST "+indexresponseBody);

res.write(indexresponseBody);
res.end();


我能够获取json,并将其打印在节点服务器控制台上。但是,当我在Firebug控制台上将此json写入response(res)对象时,我看不到此json。有人可以告诉我如何获得此回复。

最佳答案

可能是由于回调的异步性质,请尝试以下操作-

function (error, resp, body) {
    indexresponseBody = JSON.stringify(JSON.parse(body).message);
    res.writeHead(200, {'content-type':'text/html'});
    console.log("JSON returned from REST "+indexresponseBody);
    res.write(indexresponseBody);
    res.end();
}

10-05 20:50
查看更多