Skip to content

Instantly share code, notes, and snippets.

@soonsam123
Last active December 6, 2020 21:42
Show Gist options
  • Save soonsam123/4cc616362070207634790563b76fee7c to your computer and use it in GitHub Desktop.
Save soonsam123/4cc616362070207634790563b76fee7c to your computer and use it in GitHub Desktop.
NodeJS API-Part 4 / Headers middleware
const express = require("express");
const app = express();
app.listen(8000);
/**
* Adding headers to our requests.
*/
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
return res.status(200).json({});
}
next();
});
app.get("/dojos", function (req, res) {
res.send({
id: 1,
name: "KARATÊ DOJO",
teacher: "JACKSON TANAKA",
});
});
app.use((req, res, next) => {
const error = Error("Not found");
res.statusCode = 404;
res.send({ error: error.message });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment