首页 > 解决方案 > req.body 返回 null Express

问题描述

学校项目遇到问题。我正在尝试发出 POST 请求,通过 Insominia 将新用户插入表中。我不断收到用户名的空值错误。我已将我的代码发送给一位助教,但他们没有收到此错误。代码对他们来说运行良好。所以我们无法弄清楚我的问题。我想知道它是否与Insomina有关。任何帮助将不胜感激,谢谢。

错误信息:

{
  "error": {
    "message": "null value in column \"username\" of relation \"users\" violates not-null constraint",
    "status": 500
  }
}

我通过 Insomina 提出的要求:

{
    "username": "newUser",
    "password": "password"
}

index.js

app.use(express.json());

ORM 用于 User 类,createNewUser 函数用于 POST 请求。

用户.js

    /* Create a new user function for post request. Inserting user name and password.
    Returning the id, username, and password. */ 
    static async createNewUser(username, password) {
      const results = await db.query(
        `INSERT INTO users (username, password)
          VALUES ($1, $2) 
          RETURNING id, username, password`,
        [username, password]);

      console.log(results.rows);

      let { id } = results.row[0];
      return new User(id, username, password);
    }

POST 路线给我带来了麻烦,req.body 返回未定义。

用户路由.js


  /* Create a new user by requesting the body of username and password
   and returning the json.*/ 
router.post('/', async function (req, res, next) {
    try {
        console.log(req.headers);
      let id = await User.createNewUser(req.body.username, req.body.password);
      console.log(id);
      return res.json(id);
  } catch (e) {
      return next(e);
  }
  });

标题登录终端。我想知道我的问题是否在这里,因为我没有得到 Content-Type:application/json。

{
  host: 'localhost:3001',
  'user-agent': 'insomnia/2021.4.1',
  authorization: 'Basic Og==',
  accept: '*/*',
  'content-length': '51'
}

Insomina 中的标题

X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Content-Length: 121
ETag: W/"79-wzArjA/Y97Lx74leuLv1MyJkXDQ"
Date: Mon, 06 Sep 2021 16:49:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5

标签: node.jsjsonpostgresqlexpressinsomnia

解决方案


答案可能是由于缺少Content-Type标题。“Insomnia 中的标头”是您的应用程序发回的响应标头。

在 Insomnia 中,确保选择 JSON 作为Body类型:

失眠 POST 正文 JSON

选择此选项后,您还将Content-Type在选项卡中看到该集合Header

失眠 JSON 内容类型标头

设置该标头后,您的请求应成功完成


推荐阅读