我正在尝试使用express js学习postgresql,目前正在尝试将测试“名称”值发送到我的后端数据库,但是每次发送时都将其存储并作为null返回。这是我当前的server.js表达用尽了:
const express = require("express");
const app = express();
const cors = require("cors");
const pool = require("./db");
const PORT = 5000;
//
//Middleware
//
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }))
//
//Routes
//
//Add to cart
app.post("/addCart", async(req,res) =>{
try {
const { description } = req.body;
const newName = await pool.query(
"INSERT INTO products(name) VALUES($1) RETURNING *",
[description]
);
res.json(newName.rows[0]);
} catch(err){
console.error(err);
}
});
app.listen(PORT, () =>{
console.log("Express Server has started on port", {PORT});
});
这是我的邮递员尸体:
{
"name": "testtest"
}
这是返回的响应:
{
"id": 9,
"name": null
}
任何帮助将不胜感激!
答案 0 :(得分:0)
看起来您从请求主体中拉出了错误的属性。尝试将描述更改为代码中的名称:
try {
- const { description } = req.body;
+ const { name } = req.body;
const newName = await pool.query(
"INSERT INTO products(name) VALUES($1) RETURNING *",
- [description]
+ [name]
);
res.json(newName.rows[0]);