Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Cannot Post/ in express js

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");
  });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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().

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!