gpt4 book ai didi

javascript - 我的 API 路线不起作用; NodeJS

转载 作者:行者123 更新时间:2023-12-03 05:17:28 27 4
gpt4 key购买 nike

我正在使用 NodeJS 开发一个身份验证 API 系统。 /Signup API 端点工作正常,但 /authenticate 却不行。每次调用 /authenticate 端点时,即使提供了有效的用户,我也会收到错误消息:“无法验证用户”;下面是我的代码。请告诉我我在这里做错了什么

var express = require("express");
var mongoose = require("mongoose");

var User = require("../models/user");

module.exports = function (router) {
router.post('/signup', function (req,res) {
var user = new User();
user.local.username = req.body.username;
user.local.email = req.body.email;
user.local.password = req.body.password;

if (req.body.username == null || req.body.username == '' || req.body.email == null || req.body.email == '' || req.body.password == null || req.body.password == '') {
res.json({success:false, message:'Ensure username, email and password were provided'});
} else {
user.save(function (err, data) {

if (err) res.json({success:false, message:'Username or Email already exists!'});
// console.log(err.errors)
res.json({success:true, message:'New user created', data:data});
console.log(data)
});
}
})

router.post('/authenticate', function (req,res) {
User.findOne({username: req.body.username}).exec(function (err,user) {
if(err)
return res.send(err);

if (!user) {
res.json({success:false, message: 'Could not authenticate user'});
} else if(user){
var validPassword = user.comparePassword(req.body.password)
if (!validPassword) {
res.json({success:false, message: 'Could not authenticate password'});
} else{
res.json({success:true, message: 'User authenticated'});
}
}
});
});
}

编辑
用户模型:

var mongoose = require('mongoose');   
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');

// define the schema for our user model
var userSchema = new Schema({

local : {
username : {type:String,unique:true,required:true, lowercase:true},
email : {type:String,unique:true,required:true, lowercase:true},
password : String
},

created_at : {type:Date, default:Date.now},
updated_at : {type:Date, default:Date.now}

});

userSchema.pre('save', function(next){
var user = this;
var now = new Date();
user.updated_at = now;
if(!user.created_at){
user.created_at = now
}
bcrypt.hash(user.local.password, null, null, function (err, hash) {
if(err) return next(err)
user.local.password = hash;
next(); })

});

// checking if password is valid
userSchema.methods.comparePassword = function(password) {
return bcrypt.compareSync(password, this.local.password); };

// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);

最佳答案

刚刚看到错误,您的用户名位于本地。

 router.post('/authenticate', function (req,res) {
User.findOne({'local.username': req.body.username}).exec(function (err,user) {
if(err)
return res.send(err);
else{
}
});

关于javascript - 我的 API 路线不起作用; NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41547148/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com