简体   繁体   English

无法在 express js 中发布/

[英]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 .我有以下代码,并且还定义了 POST/messages 的响应,但是当我转到 /bc/add 并提交表单时,它显示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.您在中间件中声明处理程序,这不是 Express 的工作方式。

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.除此之外,从语义上讲, /bc/add//s的处理程序不是中间件,而是路由处理程序。 It's better to declare them as such explicitely, by using app.get() instead of app.use() .最好通过使用app.get()而不是app.use() () 来明确声明它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM