Created
February 8, 2011 15:28
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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();
})
+1
9 years later, this post saved me ❤
my hero!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From a noob. Where should you put such a code?