【问题标题】:node api route doesn't return any status code节点 api 路由不返回任何状态码
【发布时间】:2021-08-19 00:42:02
【问题描述】:

我创建了一个在 mongodb 上注册新用户的 api 路由。 目前它没有返回任何状态码,但我不知道为什么。

const express = require("express");
const User = require("../models/User");
const router = express.Router()

router.post("/users",async (req, res) => {
    
    // Create a user
    const user= new User({
        username: req.body.username,
        password: req.body.password
    });

    // Save user in the database
    user
        .save(user)
        .then(data => {
            
            res.status(200);
        })
        .catch(err => {
            res.status(500).send({
                message:
                    err.message || "Some error occurred while creating the user."
            });
        });
})
module.exports = router

【问题讨论】:

  • 待定状态码是什么意思?另外,为什么要将 async await 与 promise 语法混合使用?
  • 我编辑了我的问题。我没有注意到语法。谢谢你的建议。
  • 所以,现在您编辑/更改了您的问题,将res.status(200) 更改为res.status(200).send({ message: "Success" });。这应该可以解决您的问题。
  • 是的。解决了这个错误。现在它返回状态码 200。
  • 所以,请把你的问题放回原来的样子。在 stackoverflow 上,您不想编辑问题以包含答案。答案属于答案,而不是问题。

标签: node.js mongodb api express


【解决方案1】:

res.status(200) 只是设置实际发送响应时的状态。它不会自己发送响应。因此,您的服务器从未真正发送响应。如果您想发送只是状态的响应,请使用:

res.sendStatus(200);

或者,只是发送一个响应:

res.send({ message: "Success" });

默认状态已经是 200,所以您不必手动设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-16
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 2020-08-18
    • 2020-01-18
    相关资源
    最近更新 更多