Skip to content

Instantly share code, notes, and snippets.

@nilcolor
Created February 8, 2011 15:28
Show Gist options
  • Save nilcolor/816580 to your computer and use it in GitHub Desktop.
Save nilcolor/816580 to your computer and use it in GitHub Desktop.
Node.js cross-origin POST. You should response for OPTIONS request first. Something like this.
if (req.method === 'OPTIONS') {
console.log('!OPTIONS');
var headers = {};
// IE8 does not allow domains to be specified, just the *
// headers["Access-Control-Allow-Origin"] = req.headers.origin;
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
res.writeHead(200, headers);
res.end();
} else {
//...other requests
}
@lostation
Copy link

lostation commented Aug 6, 2017

@nilcolor @cameronroe YOU SAVED ME ! THANKS A LOT !!! I spent 2 days on fu** issues of preflight...

@falsy
Copy link

falsy commented Feb 22, 2018

@nilcolor @cameronroe Thank you! This is the information I really wanted!

@mirzaumersaleem
Copy link

+1 thanks man save my time and searches

@vaultdev2017
Copy link

Thanks...
this saves my time.....

@lekhoi
Copy link

lekhoi commented Jun 2, 2018

Thank you for the code, saved my weekend :-)

@guruprasad211
Copy link

i am not able to solve, my frontend is angularjs 5, searching for solution from last 5 days, please help

@rsbrum
Copy link

rsbrum commented Jun 25, 2018

@shivarajnaidu
Copy link

Simply we can use app.use(cors()) for node module

@heyjoy21
Copy link

Thanks much !! you saved alot of time..

@mazzespazze
Copy link

From a noob. Where should you put such a code?

@Asaf-S
Copy link

Asaf-S commented Oct 3, 2019

Thanks!

From a noob. Where should you put such a code?

const express = require('express');
express()
.options('', (req, res) => {
console.log('OPTIONS request!');
var headers = {};
headers["Access-Control-Allow-Origin"] = "
";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization, cache-control";
res.writeHead(200, headers);
res.end();
})

@semtagg
Copy link

semtagg commented Mar 31, 2022

+1

@bobbyconnolly
Copy link

9 years later, this post saved me ❤

@ZHAOYANG291
Copy link

my hero!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment