node.js - 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
解决方案
推荐阅读
- php - Laravel 从 URL 获取未命名的“GET”参数 id
- javascript - 如何将按钮和输入元素添加到下拉列表中
- javascript - 怎样才能让用户做一次QUIZZ?
- android - 使用毕加索将base64字符串加载到imageview中
- ruby - 如何使用.include?捕获导致相同操作的多个选项
- php - 如何对“私有”构造函数进行例外处理?
- java - 如何在 Java 8 的范围内生成具有指定大小的随机整数的列表?
- c# - Unity3D 引擎类中不应该出现一致的“CS0201”错误
- regex - 如何计算最后出现在单元格中的Google表格单元格中特定字符的出现次数作为标准?
- java - 不兼容的类型。必需:T,找到 T。为什么?