NodeJS 不会将数据返回到 jQuery.getJSON
我已经设置了 NodeJS,当我浏览到以下 URL 时它会返回数据: http://184.106.206.235
但是,当我尝试使用 $.getJSON
调用该 URL,回调显示 data
变量和 “success”
null
> 用于 textStatus
变量。
我想这可能是跨域的事情,但我很惊讶 textStatus
说 “成功”
如果是这样的话。
如果它有帮助,这里是服务器端 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");
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将 "Access-Control-Allow-Origin": "*" 属性添加到 writeHead() 调用中:
Add the "Access-Control-Allow-Origin": "*" property to your writeHead() call:
对于遇到同样问题的任何人来说,请注意,上面的解决方案对我来说只做了一个小改动:
“Content-Type”:“application/json”
而不是“text/json”。
感谢您的解决方案!这让我发疯。
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.
如果您使用 express 框架,您可以尝试以下方法之一:< br>
1.
res.contentType('json');
设置为内容类型。2.
res.send({ some: 'json' });
它将设置内容类型并为您解析它。3.
res.json({ user: 'tj' });
可能是最好的方法。希望有帮助:)
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 :)