2

I've index.html that sends post request to localhost:3000/SetUser but I always get the error XMLHttpRequest cannot load https://localhost:3000/SetUser. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost' is therefore not allowed access.

this is the code in my Angular controller

$http.post("https://localhost:3000/SetUser", {'a':'b'}).success(function(data, status, headers, config) {
 console.log('data', data);
});

and this is the code over my server.js(nodejs) app.post

app.post('/SetUser', function(req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); 
    res.end();
    console.log("New user added ", req.body);
});

I tried everything, not sure anymore what can be done to fix this. thanks!

3
  • That particular route is on the server running on port 3000 right? Commented Oct 12, 2014 at 17:44
  • I found that sometimes using * doesn't always work as expected depending on the back-end used, have you try with the address of the app instead? Commented Oct 12, 2014 at 17:56
  • @gillesc if this would be the case, you would get a specific error message. something like wildcards (*) not accepted.. (dont have the exact phrase in my head right now). My guess is, your function of you server.js never runs and your headers aren't set at all to allow cors. Commented Oct 12, 2014 at 17:58

2 Answers 2

2

make sure everything runs on the same port and it should solve the problem, and yea via his error it is understandable that hes sending a requestion from port 80 to port 3000. what stopping you from resolving your app on the same port ?

you should explain yourself better.

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

Comments

1

Take a deeper look into the network tab, browsers send a "preflight" request and this is an OPTIONS request: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

So you have to set your CORS header for this verb!

I would recommend to set it globally:

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'example.com');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
    next();
});

In addition watch for your allow-headers and complete them

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.