2

I'm developing a back-end RESTfull app with ExpressJS(Node). And reading with angularJS. I got this error on chrome.

**

XMLHttpRequest cannot load http://local.dev:3000/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://local.dev:63359' is therefore not allowed access.

**

Note : ExpressJS api working on Postman app. Postman app is successfully get data.

This is my code ANGULARJS

$http.post("http://local.dev:3000/api",{
    "username" :'JJ',
    "email" : '[email protected]'
}).then(function(mes){
    console.log(mes);
});

EXPRESSJS

router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

Thanks in advance.

1
  • Local.dev = localhost (I can't able to add as local host that's why add like local.dev.) Commented Jun 14, 2014 at 11:47

1 Answer 1

7

This is the CORS browser limitation. Your server will have to response with some headers to tell the browser cross domain access is allowed.

If you search around there are a few middleware as node package (eg. express-cors) available. But I found sometimes they does not work as what I want. So here is the one I used:

app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
   res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Cache-Control");
   if (req.method === 'OPTIONS') {
    res.statusCode = 204;
    return res.end();
  } else {
    return next();
  }
});

By the way, you will have to use this middleware for the server you are accessing ( http://local.dev:3000/api )

When trying to access a cross origin resource, the browser will try to make a Options request to read these special header and decide if the server allow the access. This is why, for Options request, you can response straight away without passing the flow using 'next()'.

You can also edit the list of methods allow by editing the Access-Control-Allow-Methods header.

Access-Control-Allow-Headers header is optional, you can use it to limit the headers that can be used.

Sign up to request clarification or add additional context in comments.

1 Comment

And also we need to do every get event to add next?? Like this? enable-cors.org/server_expressjs.html

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.