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

8zzbczxx  于 2024-01-08  发布在  Go
关注(0)|答案(1)|浏览(228)

当我学习新东西时,我通常会编写代码,在其中我可以使用它,但我会尽可能简单地编写代码。现在我正在学习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你能告诉问题所在吗?

  1. const express = require('express');
  2. const mongoose = require('mongoose');
  3. const bodyParser = require('body-parser');
  4. const jwt = require('jsonwebtoken');
  5. const app = express();
  6. app.use(bodyParser.json());
  7. const userSchema = new mongoose.Schema({
  8. name: { type: String, required: true },
  9. age: { type: Number, required: true },
  10. username: { type: String, required: true },
  11. });
  12. const User = mongoose.model('User', userSchema);
  13. function login(req, res){
  14. const {username} = req.body;
  15. User.findOne({ username })
  16. .then(function(doc){
  17. const userId = doc._id;
  18. const token = jwt.sign({ userId }, 'abc123', {expiresIn: 250});
  19. return res.status(200).json({status: 'success', token, data: {doc}});
  20. });
  21. }
  22. app.post('/login', login);
  23. mongoose.connect('mongodb+srv://username:[email protected]/? retryWrites=true&w=majority')
  24. .then(() => app.listen(5000))
  25. .catch(err => console.log(err));

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

jjjwad0x

jjjwad0x1#

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

  1. app.post('/login', async (req, res) => { //< Mark callback as async
  2. console.log('body=', req.body); // Make sure body parser is working
  3. try{
  4. const user = await User.findOne({ username: req.body.username }); // Use await
  5. const token = jwt.sign({ userId: user._id }, 'abc123', {expiresIn: 250});
  6. return res.status(200).json({
  7. status: 'success',
  8. token,
  9. data: user
  10. });
  11. }catch(err){
  12. console.log(err); // Error in console will tell you what's wrong
  13. return res.status(500).json({
  14. message: 'Error on server'
  15. });
  16. }
  17. });

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

  1. app.get('/users', async (req, res) => {
  2. try{
  3. const users = await User.find();
  4. return res.status(200).json({
  5. status: 'success',
  6. users : users
  7. });
  8. }catch(err){
  9. console.log(err);
  10. return res.status(500).json({
  11. message: 'Error on server'
  12. });
  13. }
  14. });

展开查看全部

相关问题