nodejs - 在要求它进入server.js后,路由返回404的错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nodejs - 在要求它进入server.js后,路由返回404的错误相关的知识,希望对你有一定的参考价值。
我有问题向这条路线发出请求。我不想将所有内容放在一个文件中,因为我想分开关注点。
但是当我将路由导入服务器文件时,它仍然提供404状态。请有人帮助我!
这是我的登录路线文件:
//Set up
let express = require("express");
let app = express();
let logger = require("morgan");
let bodyParser = require("body-parser");
let cors = require("cors");
let database = require("./database");
let staffModel = require("./schema");
// Endpoint for the login function
app.use(cors());
const { body, validationResult } = require('express-validator/check');
const { sanitizeBody } = require('express-validator/filter');
const { trim } = require('express-validator').validator;
app.use(bodyParser.urlencoded({extended: false})); //Parses urlencoded
bodies
app.use(bodyParser.json()); //Send JSON responses
app.use(logger('dev')); // Log requests to API using morgan
let login = require("./routes/login");
app.use("/login", login);
app.listen(8080);
console.log("Trazeapp Started, listening on port 8080");
这是我的登录路线文件。
//Set up
let express = require("express");
let router = express.Router();
router.post("/login", function(req, res){
req.body.username = trim(req.body.username);
staffModel.find({"login.username": req.body.username},
{"login.username":1,"login.password":1,"admin":1})
.then(data=> {
if (data.length == 0){
res.send({"error": "There's no staff with this username"})
} else{
// Get the individual values
let uname = data[0].login.username.toString();
let pwd = data[0].login.password.toString();
let adm = data[0].admin.toString();
// If user and password is correct
if((req.body.username == uname) && (req.body.password ==
pwd)){
//Login information is correct
//Check the privilege of who is loggin in
if(adm == "yes"){
console.log("inside yes");
res.send({"username": uname, "password": pwd,
"admin": true});
}
else if(adm == "no"){
console.log("admin is: " + adm);
res.send({"username": uname, "password": pwd,
"admin": false});
}
}
else if((req.body.username != uname) || (req.body.password
!= pwd)){
//Username and/or password is wrong
res.send({"error": "Your Username and/or Password is
wrong."});
}
}
})
.catch(err=> res.send({"error": "There's an issue with the
server."}))
});
module.exports = router;
答案
从以下位置更改路线定义:
router.post("/login", ...)
对此:
router.post("/", ...)
/login
已经在这里指定:
app.use("/login", login);
这意味着路由器中的所有路由都已使用/login
作为前缀。所以,你的代码正在为/login/login
创建一条不是你想要的路线。
仅供参考,你也可以改变这一点:
app.use("/login", login);
对此:
app.use("/", login);
虽然将整个登录路由器保持在/ login可能更有意义。
以上是关于nodejs - 在要求它进入server.js后,路由返回404的错误的主要内容,如果未能解决你的问题,请参考以下文章