【问题标题】:How can I show JSON response in Postman, GET request Express?如何在 Postman、GET request Express 中显示 JSON 响应?
【发布时间】:2021-04-18 07:56:37
【问题描述】:

我正在尝试通过 Id 使用 mongoose 和 express 获取单个用户的信息。我现在拥有的函数给了我一个 200 状态代码,但是 JSON 对象没有出现在 Postman 中我错过了什么?

我从我的文件中发布了我正在使用的控制器和模型。

控制器

const express = require("express");

const classworkRouter = express.Router();

const User = require("../../models/User");

classworkRouter.get("/:userId", (req, res) => {
    // const Id = req.params.userId;

        User.findById(req.params.userId).then((err, user)=>{
            if(err) {
                res.status(500);
                console.log("errr 500")
            } else {
                res.json({"user" : user})
            }
        })
       

})



module.exports = classworkRouter;

型号

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const ClassworkSchema = new Schema({
    name: String,
    time: Date,
    todo: String,
    isDone: false
});

const OutcomesSchema = new Schema({
    name: String,
    time: Date,
    todo: String, 
    isDone: false,
    isApproved: false
})

const MeetupSchema = new Schema({
    name: String,
    time: Date,
    location: String,
    attended: false
})
const UserSchema = new Schema({
    name: {
      type: String,
      required: true
    },
    email: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true
    },
    date: {
      type: Date,
      default: Date.now
    },
    classwork: [ClassworkSchema],
    outcomes: [OutcomesSchema],
    meetups: [MeetupSchema],
  });



module.exports = User = mongoose.model('users', UserSchema);

【问题讨论】:

  • 如果找不到用户,则只需在响应中获取一个空对象
  • 你检查 req.params.userId 值了吗?

标签: node.js json express mongoose postman


【解决方案1】:

验证事项:

  1. req.params.userId 不为空。
  2. 当您使用findById 时,userId 必须是有效的 ObjectId。即,它必须是mongoose.Types.ObjectId 类型。
  3. 检查您是否传递了现有的 userId。

因此,您可以这样做:

var ObjectId = require('mongoose').Types.ObjectId;
classworkRouter.get("/:userId", (req, res) => {
      const { userId } = req.params;

        if(!userId){
           return res.status(400).json({//handle error })
        }
       
        if(!ObjectId.isValid(userId)){
           return res.status(400).json({//handle error })
        }

        User.findById(userId,(err, user) {
            if(err) {
                res.status(500);
                console.log("errr 500")
            } else {
                if(!user)
                res.status(400).json({message:"user not found"});

                res.status(200).json({"user" : user})
            }
        })
       

})

【讨论】:

  • 这很有效,谢谢,如果我想访问用户中的嵌套对象并获取该信息,我该怎么做呢?
  • 您可以使用点运算符简单地访问它,例如 -> user.nestedObject.fieldNameuser[nestedObject["fieldName"]]
【解决方案2】:

您在 then 中指定了两个参数,但 then 有 1 个参数 - 解析 Promise 的结果。如果你需要得到一个可能的错误你需要使用catch:

User.findById(req.params.userId)
    .then((user)=>{
    if(!user) {
         res.status(404).end();
         console.log("user not found")
    } else {
        res.json({"user" : user})
    }})
    .catch((err)=>{
        res.status(500).end();
        console.log("errr 500")
    })

【讨论】:

    猜你喜欢
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多