0

我在javascript中有这段代码

var url = 'http://mydomain.com:3000';
url += "/user";

jQuery.ajax({
  url: url,
  type: "GET",
  dataType: "jsonp",
  async: false,
  success: function (data) {alert(1);
    console.log(data);
  }
});

我的网站在http://mydomain.com:80上运行,因此它们不在同一台服务器上。

http://mydomain.com:3000由 nodejs 提供,代码

app.get('/user',function(req,res){    
  var result = {
    result:-1
  };
  res.json(result);
  res.writeHead(200, {"Content-Type": "application/json"});
});

当我调用 ajax 时,我从 chrome 预览响应中得到

{
  "result": -1
}

但是在javascript的控制台中我得到了错误

Uncaught SyntaxError: Unexpected token : user:2

而且我没有收到任何警报消息。

我什至在nodejs中尝试过

res.end("'"+JSON.stringify(result)+"'");

并且 chrome 预览响应是

'{"result":-1}'

并且控制台错误消失了,但仍然没有触发警报

4

1 回答 1

0

res.json()立即发送响应。您必须在使用它之前设置标题。

res.json(result);
res.writeHead(200, {"Content-Type": "application/json"}); //Response already sent before.

所以res.writeHead()不设置标题作为响应。您收到的错误意味着您的响应中有一些非法字符代码。

Uncaught SyntaxError: Unexpected token : user:2

Try setting headers before, browser will then correctly identify your message as JSON.

Update

On checking your code again I saw that you are sending response as res.json() but in your AJAX recieving it as jsonp. The two are different json and jsonp. There is a res.jsonp() you can use in node or change datatype in your AJAX query as json.

于 2013-03-09T13:52:58.153 回答