【问题标题】:req.body returning null Expressreq.body 返回 null Express
【发布时间】:2021-11-03 18:00:37
【问题描述】:

学校项目遇到问题。我正在尝试发出 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());

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

user.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 返回 undefined。

userRoutes.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

【问题讨论】:

  • 我同意这可能是缺少的 Content-Type 标头。您如何在浏览器中或通过curl 或...创建请求?
  • @HeikoTheißen 我刚做了失眠症

标签: node.js json postgresql express insomnia


【解决方案1】:

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

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

选中此选项后,您还会在Header 选项卡中看到Content-Type 设置:

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

【讨论】:

  • 谢谢你的工作。没有在 Insomina 上正确设置内容类型。
猜你喜欢
  • 2017-08-30
  • 2021-08-08
  • 1970-01-01
  • 2021-05-05
  • 2020-09-21
  • 2020-08-07
  • 2021-03-08
  • 2021-07-23
  • 1970-01-01
相关资源
最近更新 更多