【问题标题】:JSONP undefined in node.js, use .send will cause unexpected token errornode.js 中未定义 JSONP,使用 .send 会导致意外令牌错误
【发布时间】:2013-10-09 08:47:17
【问题描述】:

我在我的 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”。我也不能使用发送,因为我在客户端使用 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 的位置,因此它不会在客户端抛出意外的令牌错误。(现在它从 json 和jsonp 问题)。

【问题讨论】:

    标签: jquery json node.js express jsonp


    【解决方案1】:

    我认为你误解了 jsonp 是什么。它不是一个可以绕过同源策略的神奇 ajax。它适用于这样的浏览器:

    1. 获取jsonp数据的url。
    2. 创建一个处理 jsonp 数据的函数。
    3. 将函数名称作为参数附加到 jsonp url。
    4. 在 DOM 中使用该 url 的 src 属性创建一个脚本标记。
    5. jsonp 服务器看到有请求进来,将 json 数据包装在对函数参数的调用中。
    6. 脚本加载到您的页面并执行函数。

    虽然 jQuery 和其他一些框架使这个看起来像一个 XMLHttpRequest,但它远非如此。

    仅仅因为您必须在客户端使用 jsonp 并不意味着您必须在 node.js 中使用它。您是否查看了外部服务器的 API 并确定您已尝试创建正确的 GET、PUT 或 POST 请求?

    【讨论】:

    • 感谢您的帮助 :-) 您是对的。但是,如果我使用 app.send() 而不是 app.jsonp(),它会给我一个关于意外令牌“:”的错误。我读了一些帖子,似乎是 jsonp 与 json 的问题......我该怎么办?
    • 你在使用 Express 吗?
    • 是的。我正在使用 Express。
    • 好的。我要深入研究一下,然后再发表评论。
    • 谢谢!它不是 server.js 文件。这是一个中间件文件。
    猜你喜欢
    • 2014-05-27
    • 2013-01-28
    • 2014-02-19
    • 2013-09-20
    • 2014-11-24
    • 2012-11-18
    • 2011-11-09
    • 2016-10-09
    • 1970-01-01
    相关资源
    最近更新 更多