JSONP在node.js中未定义,使用.send会导致意外的令牌错误

我在我的node.js函数中使用JSONP:

this.send(JSON.stringify({ type: 'hello', username: this.data('username'), friends: friends })); 

但是,它给了我一个意想不到的令牌“:”错误(我没有看到在JSON中)。 在阅读这篇文章之后: jsonp中的'Uncaught SyntaxError:Unexpected token:'

我发现它可能是一个JSON / JSONP的问题。 所以我改变了我的代码:

 this.jsonp(JSON.stringify({ type: 'hello', username: this.data('username'), friends: friends })); 

但是,它说这没有方法“jsonp”。 我不能使用发送,因为我在客户端使用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(); } }; 

看起来好像在调用里面的send函数,但是我找不到在哪里把这个json改成jsonp,所以它不会在客户端抛出我意想不到的令牌错误(自从json和jsonp问题出现之后) 。

我想你是误解了什么jsonp。 这不是一个神奇的ajax可以绕过同样的来源政策。 它在这样的浏览器中工作:

  1. 获取jsonp数据的url。
  2. 创build一个将处理jsonp数据的函数。
  3. 将函数名称作为参数附加到jsonp url。
  4. 在DOM中创build一个具有该URL的src属性的脚本标记。
  5. jsonp服务器发现一个请求已经进入,并在调用函数参数时包装了json数据。
  6. 该脚本加载到您的页面上并执行该function。

尽pipejQuery和其他一些框架使得这个LOOK看起来像一个XMLHttpRequest,但它远非如此。

仅仅因为你不得不在客户端使用jsonp并不意味着你必须在节点中完成。 你有没有看过外部服务器的API,并确保你已经尝试创build一个正确的GET,PUT或POST请求?