我在我的 node.js 函数中使用 JSONP:
this.send(JSON.stringify({
type: 'hello',
username: this.data('username'),
friends: friends
}));
但是,它给了我一个意外的标记“:”错误(我在 json 中没有看到)。读完这篇文章后:The 'Uncaught SyntaxError: Unexpected token : ' in jsonp
我发现这可能是 json/jsonp 问题。所以我将代码更改为:
this.jsonp(JSON.stringify({
type: 'hello',
username: this.data('username'),
friends: friends
}));
但是,它说没有方法“jsonp”。我也无法使用 send ,因为我在客户端使用 jsonp 。这很奇怪,因为我可以在除了这里之外的其他地方使用 jsonp 。以下是 user.js 文件中的一些函数。
User.prototype.send = function(code, message, callback) {
this._send('listener', code, message, callback);
};
User.prototype._send = function(type, code, message, callback) {
if(!message && typeof code != 'number') {
callback = message;
message = code;
code = 200;
}
if(typeof message != 'string')
message = JSON.stringify(message);
if(type == 'connection' && this.connection) {
this.connection.writeHead(code || 200, {
'Content-Type': 'application/json',
'Content-Length': message.length
});
this.connection.end(message);
} else {
if(!this.listeners.length)
return this.message_queue.push(arguments);
var cx = this.listeners.slice(), conn;
this.listeners = [];
while(conn = cx.shift()) {
conn.writeHead(code || 200, {
'Content-Type': 'application/json',
'Content-Length': message.length
});
conn.end(message);
}
if(callback) callback();
}
};
看起来它正在内部调用发送函数,但是,我找不到在哪里将此 json 更改为 jsonp,因此它不会在客户端抛出意外的 token 错误。(现在它确实如此,因为 json 和jsonp 问题)。
最佳答案
我认为您误解了 jsonp 是什么。并不是什么神奇的ajax可以绕过同源策略。它在这样的浏览器中工作:
- 获取jsonp数据的url。
- 创建一个处理 jsonp 数据的函数。
- 将函数名称作为参数附加到 jsonp url。
- 使用该网址的 src 属性在 DOM 中创建一个脚本标记。
- jsonp 服务器发现请求已传入,并将 json 数据包装在对函数参数的调用中。
- 该脚本会加载到您的页面上并执行该函数。
虽然 jQuery 和其他一些框架使它看起来像 XMLHttpRequest,但它却远非如此。
仅仅因为您必须在客户端使用 jsonp 并不意味着您必须在 Node 中执行此操作。您是否查看过外部服务器的 API 并确保您已尝试创建正确的 GET、PUT 或 POST 请求?
关于jquery - Node.js 中未定义 JSONP,使用 .send 会导致意外的 token 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19145888/