You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中查询Postgres的函数执行两次问题求助

解决Node.js HTTP服务中数据库查询执行两次的问题

问题现象

刷新页面时控制台会两次打印"DONE",数据库查询逻辑也会执行两次。

原因分析

浏览器加载页面时,默认会自动发起一次/favicon.ico请求用于获取网站图标,这会触发HTTP服务器的两次请求处理流程,进而导致数据库查询和响应逻辑执行两次。

修复方案

在请求处理函数中判断请求URL,忽略对/favicon.ico的请求;同时规范变量声明,避免全局变量污染:

// query the db
const rate = () => pool
    .query(rateQuery)
    .then(res => res.rows[0])
    .catch(err => console.log('error: ', err.stack))

const app = http.createServer((request, response) => {
    // 忽略favicon.ico请求
    if (request.url === '/favicon.ico') {
        response.writeHead(204);
        response.end();
        return;
    }

    // set response header
    response.writeHead(200, { 'Content-Type': 'text/html' });

    // get result of promise
    const r = rate()
        .then(res => {
            response.write(JSON.stringify(res), () => {
                console.log("DONE");
                response.end();
            });
        })
        .catch(err => console.log('error: ', err.stack))
});

app.listen(3000);

说明

添加/favicon.ico的判断后,只有当请求业务路径(比如根路径/)时才会执行数据库查询,浏览器的图标请求会被直接返回204状态码并结束响应,不会触发查询逻辑,从而解决执行两次的问题。

内容的提问来源于stack exchange,提问作者Hunter Boyd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:30:58