【发布时间】: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