javascript - postman 没有收到 POST 的回复

标签 javascript node.js postgresql express

使用 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)。

postman screenshot

知道发生了什么吗?谢谢。

最佳答案

简而言之 - 当您的代码运行时,它会到达 pool.query(...) 行(这是异步函数),并且它不会等待响应,因为您没有指定你想要等待它。 解决方案是使 createEvent 函数异步:

const createEvent = async(请求,响应)

并等待数据库响应:

等待 pool.query(...)

了解更多关于async/await的信息和/或Promises

关于javascript - postman 没有收到 POST 的回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60132002/

相关文章:

javascript - 如何在 Windows 上安装 n?

javascript - Backbone Marionette 获取区域 View

javascript - 检查带有日期的键值对是否存在,如果不存在则将其推送到数组中

javascript - 从类中发出事件

在 postgreSQL 中删除重音的函数

sql - Postgres : correlated subquery with NOT EXISTS

postgresql - 如何将docker postgres镜像10.3中的pg_restore升级到10.5

javascript - Lodash 使用一个字符的值从数组创建一个数组

javascript - 在附加之前不显眼的 jQuery 设置属性 - 是否可以使用更有效的语法?

node.js - node.js 插件与 child_process 的优势