使用 Express/Node 和 Postgres(“pg”包)。
代码:
const createEvent = (request, response) => {
console.log(request.body);
const {
type,
location,
current_attendees,
total_attendees,
details,
event_date,
has_car,
has_food,
cover_charge,
contact_email,
} = request.body;
pool.query(`INSERT INTO events (type, location, current_attendees, total_attendees, details, event_date, has_car, has_food, cover_charge, contact_email) VALUES ('${type}', '${location}', ${current_attendees}, ${total_attendees}, '${details}', TO_DATE('${event_date}', 'YYYY-MM-DD'), ${has_car}, ${has_food}, ${cover_charge}, '${contact_email}')`),
(error, results) => {
if (error) {
throw error;
}
console.log(results);
response.status(201).send('Event created');
}
}
路线:
router.post('/events', db.createEvent);
该对象很好地插入到数据库中,我得到了请求主体的控制台日志,但我没有得到结果控制台日志,并且没有响应发送回 postman 。它只是超时了。
我正在发送一个普通的 JSON 对象(正文 -> 原始 -> 文本 -> JSON)。
知道发生了什么吗?谢谢。
最佳答案
简而言之 - 当您的代码运行时,它会到达 pool.query(...)
行(这是异步函数),并且它不会等待响应,因为您没有指定你想要等待它。
解决方案是使 createEvent 函数异步:
const createEvent = async(请求,响应)
并等待数据库响应:
等待 pool.query(...)
了解更多关于async/await的信息和/或Promises
关于javascript - postman 没有收到 POST 的回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60132002/