mongoose 在一个简单的代码中输入错误以获取jsonwebtoken

8zzbczxx  于 9个月前  发布在  Go
关注(0)|答案(1)|浏览(115)

当我学习新东西时,我通常会编写代码,在其中我可以使用它,但我会尽可能简单地编写代码。现在我正在学习JsonWebToken的基础知识,所以我在MongoDB中创建了一个非常小的数据库-只有几个文档,3个字段- _id,name,age和username。然后我在node.js中写了几行代码。但问题是我总是收到“TypeError:无法读取null的属性(阅读'_id')"。如果我将有效负载留空(通过删除'userId')然后我得到一个带有安全令牌的响应,但其中的data属性为null -“data”:{“doc”:null}.我使用postman来获取响应,我选择POST,然后选择raw和JSON,然后在正文部分只写{“username”:“john 25”}或{“username”:“george 15”}或{“username”:“jim 35”},然后将其发送到localhost:5000/login你能告诉问题所在吗?

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');

const app = express();

app.use(bodyParser.json());

const userSchema = new mongoose.Schema({
    name: { type: String, required: true },
    age: { type: Number, required: true },
    username: { type: String, required: true }, 
});

const User = mongoose.model('User', userSchema);

function login(req, res){
    const {username} = req.body;    
User.findOne({  username })
    .then(function(doc){ 
        const userId = doc._id;
        const token = jwt.sign({ userId }, 'abc123', {expiresIn: 250});
        return res.status(200).json({status: 'success', token, data: {doc}}); 
    });                     
}

app.post('/login', login);

mongoose.connect('mongodb+srv://username:[email protected]/?       retryWrites=true&w=majority')
.then(() => app.listen(5000))
.catch(err => console.log(err));

字符串
有没有人知道如何在响应中获取用户的实际数据?

jjjwad0x

jjjwad0x1#

你没有错误处理,所以这就是为什么你不能检测到错误。首先,确保你在Postman中发送的是有效的JSON,并且Postman头中的Content-type是正确的。
因为你还在学习,所以只需要专注于在你的路由处理程序中使用回调来让你的代码工作,那么一旦你确信它是这样工作的,你就可以把它抽象成一个函数:

app.post('/login', async (req, res) => { //< Mark callback as async
   console.log('body=', req.body); // Make sure body parser is working
   try{
      const user = await User.findOne({ username: req.body.username }); // Use await
      const token = jwt.sign({ userId: user._id }, 'abc123', {expiresIn: 250});
      return res.status(200).json({
         status: 'success', 
         token, 
         data: user 
      });
   }catch(err){
      console.log(err); // Error in console will tell you what's wrong
      return res.status(500).json({
         message: 'Error on server'
      });
   }
});

字符串
添加一个get路由以返回所有用户:

app.get('/users', async (req, res) => {
   try{
      const users = await User.find();
      return res.status(200).json({
         status: 'success', 
         users : users 
      });
   }catch(err){
      console.log(err);
      return res.status(500).json({
         message: 'Error on server'
      });
   }
});

相关问题