node.js - 如何通过 REST API 处理 MongoDB 登录?
问题描述
我不确定如何检查这些值是否与 MongoDB 数据匹配。我正在使用PUT
并尝试使用findOneAndUpdate
来检查值是否匹配。
<script>
const logindetails = new Vue({
el: '#logindetails',
data: {
email: "",
password: "",
on: Boolean
},
methods: {
login: function (e) {
e.preventDefault();
const log = {
email: this.email,
password: this.password,
}
const options = {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(log)
};
fetch('http://localhost:3000/users/${this.email}/${this.password}',
options).then(response => {
[...]
</script>
这是服务器代码(它成功连接到 MongoDB):
app.put('/students/:email/:password', (req, res, next) => {
console.log("login");
res.setHeader("Content-Type", "application/json");
db.collection('users').findOne({email: (req.params.email), password: (req.params.password)},
{$set: {on: true}})
.then(results => res.send(results))
.catch(err => res.send(err))
});
解决方案
我个人认为将您的用户名和密码作为查询字符串不是一个好主意,因为它会损害 restful api 约定。如果没有正文通过,则使用 put 请求是没有意义的。此外,在登录情况下发布请求会更有意义。无论如何我离题了,这里是进行身份验证的常用步骤。
1.(客户端)在获取请求的正文中发送电子邮件和密码
//something like this
const body = { email, password };
const response = await fetch(
"http://localhost:5000/authentication/login",
{
method: "POST",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(body)
}
);
2. (服务器端 -确保您使用 app.use(express.json()) 访问 req.body)
//defining middleware to access req.body
app.use(express.json());
app.post("/authentication/login", async(req,res) =>{
//1. destructure email and password
const {email, password} = req.body
//2. check if user doesn't exist
const user = await db.user.find({user_email: email})
if(!user){
return res.status(401).send("User does not exist");
}
//3. Check if password is the same as the password in the database
if(password !== user.password){
return res.status(401).send("Wrong Credential")
}
//4. This is up to you when the user is authenticated
res.json(`Welcome back ${email}`);
})
推荐阅读
- java - Finch Robot (Java) - 轻按时应亮起并说出颜色
- node.js - 从 Yelp API 插入 Json 对象
- laravel - Laravel Mix 不结合样式
- c - 验证输入并再次询问是否无效
- google-apps-script - 对从可点击图像触发的绑定脚本中的电子表格的引用
- solr - Solr 到 Application Insights
- c - 持续写入文件是否会损害程序的性能?
- asp.net - 在 UpdatePanel 中使用 GridView 时数据不同步
- c# - 比较列表中的两个项目,然后在索引处拆分为较小的列表
- c - 向 lua 5.2 源代码添加可选的“全局”关键字