NodeJS HTTP request from AngularJS

别说谁变了你拦得住时间么 提交于 2020-01-06 04:13:06

问题


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.

Backend (NodeJS):

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

Frontend (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 :, 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.

Mattias


回答1:


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', '*');



回答2:


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




回答3:


Use res.status(status).json(obj) instead of res.json(status, obj)



来源:https://stackoverflow.com/questions/19821272/nodejs-http-request-from-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!