[ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置 headers - 尝试请求时出错

[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client - Error when trying request

我在通过邮递员执行 GET 请求时遇到此错误,该请求是一个简单的 SELECT 查询:

(node:4804) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:558:11)
at ServerResponse.header (C:\Users\lurrechaga\source\repos\Infraestructuras\InfraestructurasAPI\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (C:\Users\lurrechaga\source\repos\Infraestructuras\InfraestructurasAPI\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Users\lurrechaga\source\repos\Infraestructuras\InfraestructurasAPI\node_modules\express\lib\response.js:267:15)
at C:\Users\lurrechaga\source\repos\Infraestructuras\InfraestructurasAPI\SensoresControll\api.js:40:18
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:4804) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:4804) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我一直在寻找这个错误,发现有人遗漏了 return,有多个异步函数被抛出或遗漏了 try catch,我找不到适合我的解决方案。

我在本地计算机上使用 Express,body-parser 和 SQL 服务器 Express

这是发出请求时使用的代码:

要求:

http://localhost:8090/api/grafico/datos/temperatura/medicionAire/2059E7

API.js:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use('/api', router);

router.use((request, response, next) => {
console.log('middleware');
console.log(next());
next();
});

router.route('/grafico/datos/:medicion/:tipoMedicion/:id').get((request, response) => {
console.log("graficodato");
Db.getMedicionGrafico(request.params.medicion, request.params.tipoMedicion, request.params.id).then((data) => {
    response.json(data);
})})

函数API.js:

var config = require('./dbconfig');
const sql = require('mssql');
.
.
.
async function getMedicionGrafico(medicion, tipoMedicion, id) {
try {
    console.log("agetmedG");
    
    let pool = await sql.connect(config);
    let medicionSensor = await pool.request()
        .input('input_medicion', sql.VarChar, medicion)
        .input('input_tipoMedicion', sql.VarChar, tipoMedicion)
        .input('input_id', sql.VarChar, id)
        .query("SELECT TOP 100  " + medicion + " FROM " + tipoMedicion + " WHERE @input_id = id ORDER BY fecha DESC;");
    return medicionSensor.recordsets;
}
catch (error) {

    console.log(error);
}}

配置:

const config = {
user: 'RealUSer', // sql user
password: 'RealPasswordForsure', //sql user password
server: 'localhost', 
database: 'SensoresAire',
options: {
    trustedconnection: true,
    enableArithAbort: true,
    instancename: 'SQLEXPRESS'  // SQL Server instance name
},
port: 1433
}

module.exports = config;

从您的 api.js 中删除 console.log(next());。即使它在 console.log 内,next() 函数也被消耗了,然后在另一行上您尝试第二次消耗它。这就是问题所在。