问题描述
我目前正在使用前端的AngularJS和后端的Express开发Node.js的Web应用程序.我在从前端请求后端API时遇到了麻烦,希望你们能为我提供帮助.
I'm currently developing a web application using AngularJS on the fronted and NodeJS on the backend with express. I've had trouble requesting my backend API from the fronted however and hope you guys can help me.
后端(NodeJS):
app.get('/test', function(req, res) {
res.json(200, {'test': 'it works!'})
})
前端(AngularJS):
myApp.controller('myController', function($scope, $http) {
delete $httpProvider.defaults.headers.common["X-Requested-With"]
$http.get('http://localhost:5000/test').success(function(data) {
alert('Success')
}).error(function(data, status) {
alert('Error! ' + status + ' : ' + data)
})
})
刷新应用程序时,我会收到一条警告:错误!0:
,但是,当我使用curl或浏览器请求后端时,我又得到了测试字典.前端似乎能够访问后端,因为我在后端日志中看到它已经完成了一个请求并得到了返回,但是萤火虫说响应为空,我该怎么办?
When I refresh the app I get an alert saying: Error! 0 :
, however, when I request the backend with curl or by the browser, I get the test dict back. The frontend seems to be able to access the backend though because I see it in my backend log that it's done a request and got something back, but firebug says that the response is empty, what should I do?
非常感谢,如果您需要我提供更多信息,请告诉我.
Thanks so much, let me know if you need more info from me.
马蒂亚斯
推荐答案
请确保您的前端服务器和后端服务器具有相同的来源(协议,主机和端口).如果不是,那么由于您提出跨域的ajax请求,因此您不会收到响应.在这种情况下,您应该从后端发送特殊的标头以允许它:
Make sure that your frontend and backend servers have the same origin (protocol, host and port). If not, then you does not recieve response since you make cross-origin ajax request. In this case you should send special header from your backend to allow it:
Access-Control-Allow-Origin: *
您可以使用以下代码添加响应标头:
You can add response header with the following code:
res.set('Access-Control-Allow-Origin', '*');
这篇关于来自AngularJS的NodeJS HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!