【问题标题】:NodeJS return JSONP NOT using expressNodeJS 不使用 express 返回 JSONP
【发布时间】:2013-11-14 05:56:44
【问题描述】:

我正在尝试调用我的 nodejs 服务器并显示来自 angularjs 应用程序的结果。我一直在关注一个示例,但是当我更改我的代码的示例代码时,它总是调用错误回调。我感觉我的服务器有问题,但我无法让它工作,它的 nodejs 没有 express 或其他库,所有其他答案都涉及使用 express。不使用快递如何让它工作?

angularjs 中的代码,我在这里调用服务器:

app.controller('Main', function ($scope, $http) {
    $scope.init = function() {        
        //var api = 'http://api.trakt.tv/calendar/premieres.json/7c989229f2fa626832e7576eb59820e9/20131103/30/?callback=JSON_CALLBACK';        
        $http.jsonp('http://localhost:8888/selectAllLocations?callback=JSON_CALLBACK').success(function(data) {
            console.log(data);
        }).error(function(error) {
            console.log('My error: ' + error);
        });
    };

});

如果我使用 var api 中的值,结果是好的,并且调用成功,而不是我的。

这是我的 nodejs 服务器中的代码。

var result = sequelize.query(query, null, options, parameters)
.success(function (rows) {        
    if (type == 'select') {
        response.writeHead(200, { "Content-Type": "application/json" });
        response.write(JSON.stringify(rows));
        response.end();
    } else if (type == 'modify') {
        response.writeHead(200, { "Content-Type": "text/html" });
        response.write("Query was successful");
        response.end();
    }
}
).error(function (e) {
    console.log("An error occured: ", e);
    response.writeHead(404, { "Content-Type": "text/html" });
    response.write("There was an error man, shits on fire yo ---> " + e);
    response.end();
}
);

我很确定我必须将 json 结果包装在一个函数中,但我不知道如何,我什至不知道函数名称,因为这是我在服务器中得到的全部内容:

路径:/selectAllLocations 参数:{"callback":"angular.callbacks._0"}

我知道我返回的是纯 json,我可以在我的回复中看到它在 chrome 中,所以,有一些东西阻止它调用成功函数。有人能指出我正确的方向吗?

【问题讨论】:

    标签: javascript json node.js angularjs


    【解决方案1】:

    函数名被指定为callback参数。

     response.write(params.callback + '(' + JSON.stringify(rows) + ')');
    

    【讨论】:

    • 你是对的!那行得通!我得到的 {"callback":"angular.callbacks._0"} 是 angularjs 如何重命名回调,以及接收到的参数中的另一个值,现在这一切都说得通了。我是否必须将所有答案都包含在该函数中,即使我没有返回 json?
    • 另外,我开始质疑我是否正确地不使用像 express 这样的 nodejs 框架,因为这里的所有问题都在使用它。
    • @Toddy 由于您正在编写一个 Web 服务,我建议您使用 restify,它类似于 express,但不太面向构建网页,而更面向服务。至少,这会为您提供正确的输出格式(回调和所有)。
    • 谢谢丹,我想你是对的。我读到了它,但决定按原样使用节点来学习 javascript,我要重写,现在我了解了更多关于 javascript 的东西。如果可以的话,我会支持你!
    • 这个答案基本正确,但我也喜欢在返回 JSONP 时设置 Content-Type: "application/javascript",因为它不再是真正返回的 JSON 数据。
    猜你喜欢
    • 2016-12-08
    • 2020-09-16
    • 1970-01-01
    • 2017-06-13
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    相关资源
    最近更新 更多