Express - NodeJS - Error: Cannot set headers after they are sent to the client
Express - NodeJS - Error: Cannot set headers after they are sent to the client
我有一个项目有问题。我有一个外部 API 需要调用它来获取一些数据。此 API 调用分两步进行。首先,我向他们发送我的数据。他们在 6-12 秒内计算出结果。所以我添加了一个每秒执行一次的间隔,并向外部 API 询问结果。
我在询问结果之前发回了一个 400 状态码。这样前端应用程序就可以继续进行,不需要等待计算结果。
但是在发送给客户端后,我总是收到一个错误,指出我无法设置headers。
我试图删除 catch 块内的响应。但这也无济于事。如果我从第二个 Axios 调用中删除 headers,我会从外部服务器收到 'Unauthorized' 错误。
我还尝试在函数的开头创建一个 axios 实例,并在那里设置 headers。然后将该实例用于两个调用。但是这里仍然存在错误。
(node:37609) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:561:11)
at ServerResponse.header (/Users/stephen/Documents/projects/test-api/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/Users/stephen/Documents/projects/test-api/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Users/stephen/Documents/projects/test-api/node_modules/express/lib/response.js:267:15)
at /Users/stephen/Documents/projects/test-api/routes/blue.js:143:45
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async Timeout._onTimeout (/Users/stephen/Documents/projects/test-api/routes/blue.js:107:9)
(Use node --trace-warnings ...
to show where the warning was created)
(node:37609) 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: 2)
(node:37609) [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.
router.post('/calculate/:plotId', verify, async (req, res) => {
const info = req.body;
const auth = `Basic ${Buffer.from(`${process.env.USERNAME}:${process.env.PASSWORD}`).toString('base64')}`;
const headers = {
Authorization: auth,
'Content-Type': 'text/plain; charset=utf-8',
Host: 'test.app.be',
};
await axios.post('https://test.app.be/label', info, {
headers,
}).then(async (response) => {
res.status(201).json({
message: 'blue label sended!',
});
async function getResult(key) {
const interval = setInterval(async () => {
await axios.get(`https://test.app.be/result/${key}`, {
headers,
}).then(async (resp) => {
// Calculating Blue score failed
if (resp.data.status && resp.data.status === 'failed') {
clearInterval(interval);
}
const data = resp.data.ontwerp;
if (!data) return;
clearInterval(interval);
}).catch((error) => {
res.status(400).json({
message: error,
});
clearInterval(interval);
});
}, 1000);
}
getResult(response.data[0].result_id);
}).catch((error) => {
res.status(400).json({
error,
});
});
});
axios.post....res.status(201)
- 第一个 res.status
async function getResult(key) ... axios.get...catch(...res.status(400))
- 第二
如果您 axios.post
得到解决但 axios.get
被拒绝,您将进入第二个 res.status
调用。
res.send
或 res.status
不能像 return
那样工作 - 函数继续运行。
我有一个项目有问题。我有一个外部 API 需要调用它来获取一些数据。此 API 调用分两步进行。首先,我向他们发送我的数据。他们在 6-12 秒内计算出结果。所以我添加了一个每秒执行一次的间隔,并向外部 API 询问结果。
我在询问结果之前发回了一个 400 状态码。这样前端应用程序就可以继续进行,不需要等待计算结果。
但是在发送给客户端后,我总是收到一个错误,指出我无法设置headers。
我试图删除 catch 块内的响应。但这也无济于事。如果我从第二个 Axios 调用中删除 headers,我会从外部服务器收到 'Unauthorized' 错误。
我还尝试在函数的开头创建一个 axios 实例,并在那里设置 headers。然后将该实例用于两个调用。但是这里仍然存在错误。
(node:37609) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:561:11) at ServerResponse.header (/Users/stephen/Documents/projects/test-api/node_modules/express/lib/response.js:771:10) at ServerResponse.send (/Users/stephen/Documents/projects/test-api/node_modules/express/lib/response.js:170:12) at ServerResponse.json (/Users/stephen/Documents/projects/test-api/node_modules/express/lib/response.js:267:15) at /Users/stephen/Documents/projects/test-api/routes/blue.js:143:45 at processTicksAndRejections (internal/process/task_queues.js:95:5) at async Timeout._onTimeout (/Users/stephen/Documents/projects/test-api/routes/blue.js:107:9) (Use
node --trace-warnings ...
to show where the warning was created) (node:37609) 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: 2) (node:37609) [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.
router.post('/calculate/:plotId', verify, async (req, res) => {
const info = req.body;
const auth = `Basic ${Buffer.from(`${process.env.USERNAME}:${process.env.PASSWORD}`).toString('base64')}`;
const headers = {
Authorization: auth,
'Content-Type': 'text/plain; charset=utf-8',
Host: 'test.app.be',
};
await axios.post('https://test.app.be/label', info, {
headers,
}).then(async (response) => {
res.status(201).json({
message: 'blue label sended!',
});
async function getResult(key) {
const interval = setInterval(async () => {
await axios.get(`https://test.app.be/result/${key}`, {
headers,
}).then(async (resp) => {
// Calculating Blue score failed
if (resp.data.status && resp.data.status === 'failed') {
clearInterval(interval);
}
const data = resp.data.ontwerp;
if (!data) return;
clearInterval(interval);
}).catch((error) => {
res.status(400).json({
message: error,
});
clearInterval(interval);
});
}, 1000);
}
getResult(response.data[0].result_id);
}).catch((error) => {
res.status(400).json({
error,
});
});
});
axios.post....res.status(201)
- 第一个 res.status
async function getResult(key) ... axios.get...catch(...res.status(400))
- 第二
如果您 axios.post
得到解决但 axios.get
被拒绝,您将进入第二个 res.status
调用。
res.send
或 res.status
不能像 return
那样工作 - 函数继续运行。