NodeJS won't return data to jQuery.getJSON

房东的猫 提交于 2019-12-03 09:16:51

问题


I've set up NodeJS and it's returning data when I browse to the URL: http://184.106.206.235

However, when I try to call that URL using $.getJSON, the callback shows null for the data variable and "success" for the textStatus variable.

I imagine this could be a cross-domain thing, but I'm surprised that the textStatus says "success" if that's the case.

In case it's helpful, here's the server-side JS:

http.createServer(function(req, res){
  var output = {message: "Hello World!"};
  var body = JSON.stringify(output);

  res.writeHead(200, {'Content-Type': 'application/json', 'Content-Length': body.length});
  res.end(body);
}).listen(80, "184.106.206.235");

Any ideas?


回答1:


Add the "Access-Control-Allow-Origin": "*" property to your writeHead() call:

res.writeHead(200, {
  "Content-Type": "application/json",
  "Access-Control-Allow-Origin": "*"
});



回答2:


Just a note for anyone having the same problem, the solution above worked for me with one minor alteration:

"Content-Type": "application/json"

Not "text/json".

Thanks for the solution! It was driving me crazy.




回答3:


if you are using express framework you can try one of the following:
1. res.contentType('json'); to set to content type.
2. res.send({ some: 'json' }); that will set the content type and parse it for you.
3. res.json({ user: 'tj' }); probably the best way to do it.

hope it helps :)



来源:https://stackoverflow.com/questions/3295040/nodejs-wont-return-data-to-jquery-getjson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!