我有一个简单的 CRUD 应用程序,可以让用户注册和登录 在 General.js 中有一个注册端点,这工作正常并且登录打印
"message": "登录无效。请检查用户名和密码"
- index.js - router - - general.js - - auth_users.js - - booksdb.js
在邮递员上注册
当我在 auth_users.js 中登录端点时
这是auth_users.js的登录代码,它有登录端点,主要是负责登录的express函数regd_users.post()
const express = require('express');
const jwt = require('jsonwebtoken');
let books = require("./booksdb.js");
const regd_users = express.Router();
let users = [];
const isValid = (username)=>{ //returns boolean
//write code to check is the username is valid
let userswithsamename = users.filter((user)=>{
return user.username === username
});
if(userswithsamename.length > 0){
return true;
} else {
return false;
}
}
const authenticatedUser = (username,password)=>{ //returns boolean
//write code to check if username and password match the one we have in records.
let validusers = users.filter((user)=>{
return (users.username === username &&users.password === password)
});
if(validusers.length > 0){
return true;
} else {
return false;
}
}
//only registered users can login
regd_users.post("/login", (req,res) => {
const username = req.query.username;
const password = req.query.password;
if (!username || !password) {
return res.status(404).json({message: "Error logging in"});
}
if (authenticatedUser(username,password)) {
let accessToken = jwt.sign({
data: password
}, 'access', { expiresIn: 60 * 60 });
req.session.authorization = {
accessToken,username
}
return res.status(200).send("User successfully logged in");
} else {
return res.status(208).json({message: "Invalid Login. Check username and password"});
}
});
// Add a book review
regd_users.put("/auth/review/:isbn", (req, res) => {
//Write your code here
return res.status(300).json({message: "Yet to be implemented"});
});
module.exports.authenticated = regd_users;
module.exports.isValid = isValid;
module.exports.users = users; Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
根据提供的代码,似乎存在可能导致“无效登录”消息的问题。
在authentiatedUser函数中比较用户名和密码: 在authentiatedUser 函数中,您将过滤用户数组以查找匹配的用户名和密码。但是,过滤功能存在问题。不应使用 users.username 和 users.password,而应使用 user.username 和 user.password。该变量应该是单数,因为它代表迭代过程中 users 数组中的每个元素。
更改此行:
至: