Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
1  
alter('Success') should be alert('Success') –  Vadim Nov 6 '13 at 19:52
    
Do you serve your frontend pages from the same server as your backend runs? –  Vadim Nov 6 '13 at 20:11
    
Yes, I do now, I may not later. –  materik Nov 6 '13 at 20:46
add comment

1 Answer

up vote 1 down vote accepted

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', '*');
share|improve this answer
    
Good answer, but the note about semi-colons is not true. –  MK Safi Nov 6 '13 at 20:15
    
it worked! thanks a lot! :) –  materik Nov 6 '13 at 20:48
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.