【问题标题】:Post method isn't being called with HTML form没有使用 HTML 表单调用 Post 方法
【发布时间】:2019-06-20 04:11:42
【问题描述】:

我正在创建一个简单的登录页面,我已经使用 nodeJS 和我的 html 表单创建了我的登录路由,但是每当我在 HTML 表单上单击提交时,它都会给我一个 404 not found 错误,尽管在使用邮递员时,发布请求完美运行,我是否调用错误?

这是我在 user.js 中的路由

router.post("/login", (req, res, next) => {
  User.find({ email: req.body.email })
    .exec()
    .then(user => {
      if (user.length < 1) {
        return res.status(401).json({
          message: "Auth failed"
        });
      }
      bcrypt.compare(req.body.password, user[0].password, (err, result) => {
        if (err) {
          return res.status(401).json({
            message: "Auth failed"
          });
        }
        if (result) {
          const token = jwt.sign(
            {
              email: user[0].email,
              userId: user[0]._id
            },
            process.env.JWT_KEY,
            {
                expiresIn: "1h"
            }
          );
          return res.status(200).json({
            message: "Auth successful",
            token: token
          });
        }
        res.status(401).json({
          message: "Auth failed"
        });
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

这是我的 html 表单:

<div class="panel-heading">
    <form action="/user/login" method="post">
        Email : <input type="text" name="email"><br>
        Password : <input type="password" name="password"><br>
        <input type="submit"><br>
        <a href="register.html">Not a user?</a>
    </form>
</div>

它们都位于同一个应用目录中

这是在我的 app.js 文件中:

// Routes which should handle requests
app.use("/products", productRoutes);
app.use("/orders", orderRoutes);
app.use("/user", userRoutes);

【问题讨论】:

  • 你为什么使用 user/login 并且 user.js 是你项目的主要 js 文件?
  • @mzparacha 我用它来尝试调用我在 user.js 中创建的登录路由,不,它只是保存我的用户路由的 js 文件,我还有 app.js 和 server.js
  • 你使用过 app.use('user', loginRoute);在您的 app.js 文件中,因为在您的 html 表单中,我将“用户/登录”视为您的操作,而在您的 router.post() 中,您仅使用了“/登录”
  • 我使用 'app.use("/user", userRoutes);'在我的 app.js 文件中
  • 你导出你的服务器了吗?来自主文件,如 module.exports = app;

标签: javascript html node.js routes


【解决方案1】:

您必须从不同的服务器加载 HTML 文件。如果你需要在上面运行 XHR 请求,你需要做代理或者你需要直接使用网址。

在你的用例中使用这个:

“本地主机:3000/用户/登录”

在行动中应该做的伎俩。

【讨论】:

  • 无论何时执行此操作,我都不再收到 404 错误,但似乎什么也没有发生,我的终端也没有收到任何内容,或者说 post 请求已经发生,就像我在用邮递员做
猜你喜欢
  • 2012-01-31
  • 2011-10-09
  • 2020-07-02
  • 2020-02-02
  • 2023-01-24
  • 2011-08-10
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
相关资源
最近更新 更多