1

No matter what I try to use to set the headers it simply won't work.

The server side needs to send the response headers like this, after accepting the POST request from Frontend.

server.js

app.post('/register', (req, res) => {
   res.set({
       'Content-Type': 'application/json',
       'Access-Control-Allow-Origin': '*'
   });
   res.send('string');
   res.end();
}

The res.set() function was not the only function I tried to use.

I tried with:

res.writeHead(201, {'Access-Control-Allow-Origin': '*'}) - doesn't work

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

res.headers() - also doesn't work

It says here that it goes like this: How can I set response header on express.js assets but the answer doesn't work for me.

No matter what I tried, the server just won't respond with the CORS enabled header and I need that header property. What am I doing wrong?

Vladimir Jovanović
  • 5,143
  • 5
  • 21
  • 42
  • What are you testing the resource with? When using a browser keep in mind that on a cross-origin POST request the browser will first send a preflight request which needs to be handled properly. – Oliver Mar 27 '18 at 18:54

2 Answers2

3

Try using the cors module: https://www.npmjs.com/package/cors

var cors = require('cors')

...

app.use(cors())
Pat Needham
  • 5,698
  • 7
  • 43
  • 63
  • 1
    This is the solution. I'm trying to use less and less modules as I want to write vanilla Node.js apps, but headers in Express (when it comes to headers) simply doesn't want to work the way I imagined. Thank you, now everything is working fine. Thank you. – Vladimir Jovanović Mar 27 '18 at 19:52
0

The Access-Control-Expose-Headers response header indicates which headers can be exposed as part of the response by listing their names.

You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

res.set('Access-Control-Expose-Headers', 'Access-Control-Allow-Origin, <any-other-custom-header>, ...');
Mladen Ilić
  • 1,667
  • 1
  • 17
  • 21