2013-11-03 69 views
2

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

的代码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(); 
} 
); 

Im相当肯定我必须包装JSON结果的功能,但我不知道怎么了,我甚至不能知道该功能的名称,因为这是我在我的服务器上获取:

路径:/ selectAllLocations PARAMS:{“callback”:“angular.callbacks._0”}

我明白即时通讯返回纯json,我可以在我的回应中看到它在铬中,所以,有一些阻止它从调用成功功能。有人能指出我正确的方向吗?

回答

3

函数名称被指定为callback参数。

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

你是对的!工作! {“callback”:“angular.callbacks._0”}我得到的是,angularjs如何重命名回调,并且在接收到的参数中它的另一个值,现在这一切都合情合理。我是否必须将所有答案都包含在该函数中,即使我不返回json? – Toddy

+0

此外,即时通讯开始质疑,如果我没有使用像表达式那样使用nodejs框架,因为这里的所有问题都在使用它。 – Toddy

+0

@Toddy因为你正在编写一个web服务,我建议使用[restify](http://mcavage.me/node-restify/),它类似于表达式,但不太适合构建网页,更多的是面向朝着服务。至少,这将会照顾到输出格式正确(回调和所有)给你。 – Dan