2013-08-23 53 views
0

我使用节点JS一个有效的JSON文件中,这是我建立我的回应:语法错误

response.writeHead(200, {"Content-Type": "script"}); 
response.write(JSON.stringify({"test":"fail"})); 
response.end(); 

客户端发出JSONP请求,并在Chrome中的Safari我得到这个错误:

Resource interpreted as Script but transferred with MIME type text/plain. 
SyntaxError: Unexpected token ':' 

的浏览器可以访问它收到的响应:

{"test":"fail"} 

哪里语法错误C ome从?

回答

1

客户端正试图执行Script资源(它被解释为Script,而不是JSON)。 {"test":fail"}无效JavaScript - 请尝试在控制台中运行它。

jsonp需要客户端通常要求的回调,以便它可以正常运行。你实际上应该做这样的事情:

response.write(request.query.callback + "(" + JSON.stringify(json) + ")"); 

这将被发射以

callback12345({"test":"fail"}) 

这是有效的JavaScript,将正常运行。