【发布时间】: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