Skip to content

Commit b6d49f4

Browse files
Add middleware example 3 for require json content
1 parent a30c30b commit b6d49f4

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

middleware_example_3.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
const express = require("express");
2+
const app = express();
3+
const PORT = 3000;
4+
5+
const requireJsonContent = (req, res, next) => {
6+
if (req.headers["content-type"] !== "application/json") {
7+
res.status(400).send("Server wants application/json!");
8+
} else {
9+
next();
10+
}
11+
};
12+
13+
app.post("/", requireJsonContent, (req, res, next) => {
14+
res.send("Thanks for the JSON!");
15+
});
16+
17+
app.get("/users", function(req, res) {
18+
console.log("users list was shown");
19+
res.send("Here is a list of users:....");
20+
});
21+
22+
app.get("/books", function(req, res) {
23+
console.log("books list was shown");
24+
res.send("Here is a list of books:....");
25+
});
26+
27+
const server = app.listen(PORT, () => {
28+
console.log(`Server running at http://localhost:${PORT}`);
29+
});

0 commit comments

Comments
 (0)