I have the following code and also have defined the response for POST/messages but when I go to /bc/add and submit a form it shows that Cannot POST /messages.
Can you please explain me the reason?
Here is my code :
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/bc/add", (req, res, next) => {
console.log("In the next middleware !", req.url);
res.send(
'<form action="/messages" method="post"><input type="text" name="message"><button type="submit">Submit </button></form>'
);
app.use("/s", (req, res, next) => {
res.send("hup");
});
app.post("/messages", (req, res, next) => {
console.log(req.body);
console.log("In the middleware !", req.url);
res.redirect("/s");
});
});
app.use("/favicon.ico", (req, res, next) => {
console.log("In the middleware !", req.url);
res.sendStatus(204);
});
app.listen(3000, () => {
console.log("Server running at port 3000");
});
You are declaring handlers inside a middleware, which isn't how Express works.
The handlers need to be declared at the "top level":
app.use("/bc/add", (req, res, next) => {
console.log("In the next middleware !", req.url);
res.send(
'<form action="/messages" method="post"><input type="text" name="message"><button type="submit">Submit </button></form>'
);
}); // end of the "middleware"
app.use("/s", (req, res, next) => {
res.send("hup");
});
app.post("/messages", (req, res, next) => {
console.log(req.body);
console.log("In the middleware !", req.url);
res.redirect("/s");
});
Besides that, semantically speaking the handlers for /bc/add/ and /s aren't middleware, but route handlers. It's better to declare them as such explicitely, by using app.get() instead of app.use().