我正在创建一个应用程序,当我尝试上载图像时,它在控制台中显示此错误:(节点:23)UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头。 我该怎么解决?
我的提取:
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
我的服务器端:
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);
},
返回res.json(candy);返回以下内容:{“ errno”:-2,“ code”:“ ENOENT”,“ syscall”:“ open”,“ path”:“ ./ public / img / paomel / paomel-q6zynjrg8w45y.jpg”}
答案 0 :(得分:0)
由于此回调函数而出现此错误
sampleFile.mv(`./public${caminho}${nome}`, function(err){
if (err) {
return res.send(err)
}
});
您的代码在同步运行时从res.json(candy);
发送响应,但是当激发异步回调时,您将得到err和`return res.send(err)
解决方案
尝试此代码
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)
}}
答案 1 :(得分:0)
执行sampleFile
时发生错误。代码的其他部分需要等待sampleFile
完成。因此,您有两个错误:"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);
尝试:< / p>
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);
}
});
}
您也可以使用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);
});
}
});
}
尝试在此处/public${route}${name}
使用绝对路径进行文件上传,因为fileupload软件包不使用相对路径。