Skip to content

Instantly share code, notes, and snippets.

@kaorukobo
Last active December 2, 2021 02:51
Show Gist options
  • Save kaorukobo/8eb2658bb458d0b7619f12bd48a5d854 to your computer and use it in GitHub Desktop.
Save kaorukobo/8eb2658bb458d0b7619f12bd48a5d854 to your computer and use it in GitHub Desktop.
Example of doing Ajax request with credential under CORS (Node.js + Express)
// 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