materik materik - 1 year ago 109
AngularJS Question

NodeJS HTTP request from AngularJS

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) {
}).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.


Answer Source

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', '*');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download