[英](node:23) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I am creating an application and when I try to upload an image it gives this error in the console: (node:23) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. 我正在创建一个应用程序,当我尝试上传图像时,它在控制台中给出了此错误:(node:23)UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头。 How can I solve this?
我该如何解决?
My fetch: 我的提取:
let formData = new FormData();
formData.append('arquivo', document.querySelector('input[name="arquivo"]').files[0])
formData.append('candy', candy)
formData.append('theme', document.getElementById('candytheme').value)
fetch('https://nodemae.herokuapp.com/candy', { method: 'post', headers: {'x-auth-token': window.sessionStorage.getItem('token') }, body: formData}).then
My server side: 我的服务器端:
async store(req, res) {
let candy= req.body.candy;
let name= uniqid(doce+'-')+'.jpg';
let route= `/img/${doce}/`;
let theme= req.body.theme;
let sampleFile = req.files.arquivo;
sampleFile.mv(`./public${route}${name}`, function(err){
if (err) {
return res.send(err)
}
});
const candy = await Candy.create({
name: name,
candy: candy,
route: route,
theme: theme
});
return res.json(candy);
},
The return res.json (candy); 返回res.json(candy); returns this:{"errno":-2,"code":"ENOENT","syscall":"open","path":"./public/img/paomel/paomel-q6zynjrg8w45y.jpg"}
返回以下内容:{“ errno”:-2,“ code”:“ ENOENT”,“ syscall”:“ open”,“ path”:“ ./ public / img / paomel / paomel-q6zynjrg8w45y.jpg”}
You are getting this error because of this callback function 由于此回调函数,您收到此错误
sampleFile.mv(`./public${caminho}${nome}`, function(err){
if (err) {
return res.send(err)
}
});
Your code sends response back from res.json(candy);
您的代码从
res.json(candy);
发送回响应res.json(candy);
while running synchronously, but when asynchronous callback is fired for, You are getting err and ` return res.send(err) 在同步运行时,但是在触发异步回调时,您将得到err和`return res.send(err)
Solution 解
try this code 试试这个代码
async store(req, res)
{
try {
let doce = req.body.doce;
let nome = uniqid(doce+'-')+'.jpg';
let caminho = `/img/${doce}/`;
let tema = req.body.tema;
let sampleFile = req.files.arquivo;
await sampleFile.mv(`./public${caminho}${nome}`)
const candy = await Candy.create({
nome: nome,
doce: doce,
caminho: caminho,
tema: tema
});
return res.json(candy);
});
}catch (err) {
return res.send(err)
}}
An error occures while executing sampleFile
. 执行
sampleFile
发生错误。 Other parts of code need to wait until sampleFile
has finished. 代码的其他部分需要等到
sampleFile
完成。 So you have two errors: "errno":-2,"code":"ENOENT","syscall":"open","path":"./public/img/paomel/paomel-q6zynjrg8w45y.jpg"
(because it cannot find a file) and the second one Cannot set headers after they are sent to the client...
(because your code doesn't handle error and follows to the final return res.json(candy);
Try: 因此,您有两个错误:
"errno":-2,"code":"ENOENT","syscall":"open","path":"./public/img/paomel/paomel-q6zynjrg8w45y.jpg"
(因为它找不到文件),而第二个文件Cannot set headers after they are sent to the client...
(因为您的代码无法处理错误并遵循最终return res.json(candy);
尝试:
async store(req, res) {
let candy= req.body.candy;
let name= uniqid(doce+'-')+'.jpg';
let route= `/img/${doce}/`;
let theme= req.body.theme;
let sampleFile = req.files.arquivo;
sampleFile.mv(`./public${route}${name}`, async function(err) {
if (err) {
res.send(err)
} else {
const candy = await Candy.create({
name: name,
candy: candy,
route: route,
theme: theme
});
res.json(candy);
}
});
}
You can also use then
, without async
and await
: 您还可以使用
then
,而无需async
和await
:
store(req, res) {
let candy= req.body.candy;
let name= uniqid(doce+'-')+'.jpg';
let route= `/img/${doce}/`;
let theme= req.body.theme;
let sampleFile = req.files.arquivo;
sampleFile.mv(`./public${route}${name}`, function(err) {
if (err) {
res.send(err)
} else {
Candy.create({
name: name,
candy: candy,
route: route,
theme: theme
})
.then(function(candy) {
res.json(candy);
})
.catch(function(err) {
console.log(err);
});
}
});
}
Try to use absolute path here /public${route}${name}
for file uploading, because fileupload package doesn't use relative paths. 尝试在此处
/public${route}${name}
使用绝对路径进行文件上传,因为fileupload软件包不使用相对路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.