2

To solve error 'No Access-Control-Allow-Origin'

So I tried to search for Access-Control-Allow-Origin for Node.js, but I could only see those using Express.js api.

The warning looks like very simple: add header 'Access-Control-Allow-Origin' to the response.

Origin http://localhost is not allowed by Access-Control-Allow-Origin

Like the question above, I could also see many answers have app.use or res.header but:

  1. I don't know where the app. comes from
  2. res.header doesn't work for

    http.createServer(function (req, res){ "Something" });

Also, I tried

res.writeHead(200, {'Access-Control-Allow-Origin': '*',
'Content-Type': 'text/html','Content-Length':data.length});

But doesn't work.

I know this problem can be solved on the client side, like security off option for chrome or add on. But I want my server gives service on any client so that the users don't need to do any setting on it.

Community
  • 1
  • 1
TechNew
  • 49
  • 1
  • 6

1 Answers1

1

You should read the manual:

HTTP Node.js v0.10.30 Manual & Documentation

http.createServer(function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
});

Sidenote: app is mostly coming from var app = express(); I guess.

Daniel W.
  • 31,164
  • 13
  • 93
  • 151
  • It seems I tried this once before, and yes, don't know why, this doesn't work too. I tried to ut res.setHeader at the beginning, in the middle of req.on, and at the end of my code. Also tried to put just before the res.write(data). – TechNew Aug 04 '14 at 09:21
  • @TechNew headers need to be sent at the beginning of the response. Can verify wether the header really doesn't get sent through your browsers dev console? – Daniel W. Aug 04 '14 at 09:55