1

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

3
  • 1
    alter('Success') should be alert('Success') Commented Nov 6, 2013 at 19:52
  • Do you serve your frontend pages from the same server as your backend runs? Commented Nov 6, 2013 at 20:11
  • Yes, I do now, I may not later. Commented Nov 6, 2013 at 20:46

3 Answers 3

2

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', '*');
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer, but the note about semi-colons is not true.
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.