简体   繁体   English

来自AngularJS的NodeJS HTTP请求

[英]NodeJS HTTP request from AngularJS

I'm currently developing a web application using AngularJS on the fronted and NodeJS on the backend with express. 我目前正在开发一个Web应用程序,使用AngularJS在前端,NodeJS在后端使用express。 I've had trouble requesting my backend API from the fronted however and hope you guys can help me. 我无法从前端请求我的后端API,并希望你们能帮助我。

Backend (NodeJS): 后端(NodeJS):

app.get('/test', function(req, res) {
    res.json(200, {'test': 'it works!'})
})

Frontend (AngularJS): 前端(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)                                  
    })        
})

When I refresh the app I get an alert saying: Error! 0 : 当我刷新应用程序时,我得到一个警告说: Error! 0 : Error! 0 : , however, when I request the backend with curl or by the browser, I get the test dict back. Error! 0 :但是,当我用卷曲或浏览器请求后端时,我得到了测试字典。 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? 前端似乎能够访问后端,因为我在后端日志中看到它已经完成了请求并得到了回复,但是firebug说响应是空的,我该怎么办?

Thanks so much, let me know if you need more info from me. 非常感谢,如果您需要我的更多信息,请告诉我。

Mattias 马蒂亚斯

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. 如果没有,那么你就不会收到回复,因为你提出了跨域的ajax请求。 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', '*');

res.setHeader('Access-Control-Allow-Origin','*');

使用res.status(status).json(obj)代替res.json(status, obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM