Sahar Ben-Shushan
Sahar Ben-Shushan

Reputation: 297

Access-Control-Allow-Origin in post request - Node

I am getting a CORS error while POST request, my server is Nodejs looks like :

    var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));

app.use(function(request, response, next) {
    response.header('Access-Control-Allow-Origin', '*');
    response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    response.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

  next();
});

app.post('/InsertClient', function(request, response){

  console.log(request.body);      // your JSON
  response.send(request.body);    // echo the result back

});

I've try to set the headers already.. any ideas? Thank you all!

Upvotes: 0

Views: 479

Answers (1)

Stefano Sala
Stefano Sala

Reputation: 907

You should add a OPTIONS route at the same url as the POST: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Something like:

app.options('/InsertClient', function(request, response){
  response.sendStatus(200);
});

The browser will then first call the url with the OPTIONS method and check if it has all the appropriate cors flags, then make the actual POST request.

Upvotes: 1

Related Questions