我正在编写一个小型应用程序,该应用程序将来自React应用程序的信息提交到Express服务器的“ / download”
API,然后在其中将新文件写入本地文件系统,并使用Express res.download在客户端下载新创建的文件。
()在fs.writeFile()回调中。
我一直在使用常规的html表单提交来发布数据,但是由于复杂性的增加,我已经使用Axios进行了切换,并且它不再起作用。
奇怪的是,只有客户端上的下载似乎已停止工作。写入文件就可以了,所有控制台日志都相同(下面的“文件已下载!”日志)。当我切换回表单提交时,它继续工作,因此唯一的更改是使用Axios发送发帖请求。据我所知,一旦数据到达那里,两者之间就应该没有任何区别,但是我希望有人比我对此有更深入的了解。
除了在表单和Axios发布请求之间进行测试之外,我还尝试将Axios请求的内容类型从“ application / json”更改为“ x-www-
form-urlencoded”,以为将内容类型匹配为表单正在发送可能是答案
以下是相关应用程序的相关代码段:
server.js(Node JS)
app.post('/download', (req, res) => {
console.log("Requst data");
console.log(req.body.html);
fs.writeFile("./dist/test.txt", res.body.test,
(err) => {
if(err) {
return console.log(err);
} else{
console.log("The file was saved!");
}
let file = __dirname + '/text.txt';
/*This is the issue, the file is not downloading client side for the Axios iteration below*/
res.download(file,(err)=>{
if(err){
console.log(err);
} else {
console.log(file);
/*This logs for both View.js iterations below*/
console.log("File downloaded!");
}
});
});
})
App.js(反应)
handleSubmit(e){
e.preventDefault();
axios.post(`/download`, {test: "test"})
.then(res => {
console.log("REQUEST SENT");
})
.catch((error) => {
console.log(error);
});
}
render(){
return(
)
}
View.js(反应)
这有效:
render(){
return(
)
}
这 不会 在客户端启动下载,但是可以正常工作:
render(){
return(
)
}
我没有收到任何错误,除了客户端上的下载以外,其他所有内容似乎都正常运行。
预期结果是使用Axios在客户端下载了文件,但事实并非如此。
更新:颠簸,对此没有任何吸引力