Created
November 24, 2024 13:44
-
-
Save kasir-barati/4ecaf458fed2bce299de783448233d18 to your computer and use it in GitHub Desktop.
A simple demonstration of ExpressJS + CORS
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Document</title> | |
</head> | |
<body> | |
<script> | |
fetch("http://localhost:3000", { | |
method: "put", | |
credentials: "include", | |
}) | |
.then(console.log) | |
.catch(console.error); | |
</script> | |
</body> | |
</html> |
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
import express from "express"; | |
import cors from "cors"; | |
const app = express(); | |
// In production environment though you need to change them to your websites URL. | |
const whitelist = [ | |
"http://127.0.0.1:5500", | |
"http://127.0.0.1:3000", | |
"http://localhost:5500", | |
"http://localhost:3000", | |
]; | |
app.use( | |
cors({ | |
origin(origin, callback) { | |
if (whitelist.indexOf(origin) === -1) { | |
callback(new Error("Not allowed by CORS")); | |
return; | |
} | |
callback(null, true); | |
}, | |
methods: ["GET", "PUT", "POST"], | |
credentials: true, | |
}) | |
); | |
app.put("/", (req, res) => { | |
res.send({ message: "cors" }); | |
}); | |
app.listen(3000); | |
console.log("Server is up and running!"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Learn about how CORS works here: https://github.com/kasir-barati/graphql/blob/main/docs/security.md#cors-intricacies