Skip to content

Instantly share code, notes, and snippets.

@kasir-barati
Created November 24, 2024 13:44
Show Gist options
  • Save kasir-barati/4ecaf458fed2bce299de783448233d18 to your computer and use it in GitHub Desktop.
Save kasir-barati/4ecaf458fed2bce299de783448233d18 to your computer and use it in GitHub Desktop.
A simple demonstration of ExpressJS + CORS
<!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>
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!");
@kasir-barati
Copy link
Author

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