Last active
December 2, 2021 02:51
-
-
Save kaorukobo/8eb2658bb458d0b7619f12bd48a5d854 to your computer and use it in GitHub Desktop.
Example of doing Ajax request with credential under CORS (Node.js + Express)
This file contains hidden or 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
// npm i express cookie-parser | |
// | |
// node ajax-under-cors-example.js | |
// | |
// open http://localhost:12300/ | |
// => Step 3 will work. | |
// | |
// open http://AnotherHostNameOfYourMachine:12300/ | |
// => Step 3 will fail due to SameSite issue of Cookie. | |
// | |
const express = require('express') | |
const cookieParser = require('cookie-parser') | |
const originServer = express() | |
{ | |
originServer.get('/', (req, res) => { | |
res.send(`\ | |
<!doctype html> | |
<html lang="en"> | |
<head><title></title></head> | |
<body> | |
<ol> | |
<li>Get the credentail cookie at <a href="http://localhost:23400/get-credential">get-credential</a></li> | |
<li>Issue CORS request by clicking <button onclick="issueCors()">This</button></li> | |
<li>Finally you got: <code id="result"></code></li> | |
</ol> | |
<script> | |
function issueCors() { | |
fetch("http://localhost:23400/cors-target", { | |
method: 'POST', credentials: 'include', mode: 'cors', | |
headers: {'Content-Type': 'application/json'}, | |
body: '{}'}) | |
.then((response) => response.text()) | |
.then((text) => document.getElementById("result").innerText = text) | |
} | |
</script> | |
</body> | |
</html> | |
`) | |
}) | |
originServer.listen(12300, () => console.log(`originServer ready.`)) | |
} | |
const crossDomainServer = express() | |
{ | |
crossDomainServer.use(cookieParser()) | |
crossDomainServer.get('/get-credential', (req, res) => { | |
res.cookie('auth', '__SECRET__') | |
res.send('You got an credential cookie.') | |
}) | |
function setCorsHeader(req, res) { | |
res.set('Access-Control-Allow-Credentials', 'true') | |
res.set('Access-Control-Allow-Origin', req.get('Origin')) | |
res.set('Access-Control-Allow-Headers', 'Content-Type') | |
res.set('Access-Control-Allow-Methods', 'POST, OPTIONS') | |
res.set('Vary', 'Origin') | |
} | |
crossDomainServer.options('/cors-target', (req, res) => { | |
setCorsHeader(req, res) | |
res.sendStatus(200) | |
}) | |
crossDomainServer.post('/cors-target', (req, res) => { | |
setCorsHeader(req, res) | |
if (req.cookies.auth === '__SECRET__') { | |
res.send('You are authorized.') | |
} else { | |
res.send('No credentail!') | |
} | |
}) | |
crossDomainServer.listen(23400, () => console.log(`crossDomainServer ready.`)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment