问题描述
我的 nodejs 后端在 localhost:8080 上运行,前端在 localhost:8081 上运行,使用 http-server,我无法从服务器端下载文件到客户端,我是 node js 的新手,所以面临一些问题
我尝试了什么
我在服务器端为我所需的文件创建了一个读取流,然后将其通过管道传输到 res 对象,我还设置了一些标题:-
res.setHeader("Content-Type","image/png") // as I am trying to download a
res.setHeader("Content-disposition",`inline; filename=${filename}`);
但是还是不行
代码:-
let filename = "hello.png";
let readStream = fs.createReadStream(path.join(__dirname,"..",chatDoc.chatContent));
res.setHeader("Content-Type","image/png")
res.setHeader("Content-disposition",`inline; filename=${filename}`);
readStream.pipe(res);
cors 代码:-
const cors = require("cors");
app.use(cors({
origin: "http://localhost:8081",credentials: true,withCredentials: true
}))
前端代码:-
fetch("http://localhost:8080/downloadNow",{
method:"POST",headers:{
"Content-Type":"application/json"
},body:JSON.stringify({
chatId:chatId
}),credentials:"include"
})
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
})
前端响应:- 我收到了服务器的成功响应,但没有下载文件。
请帮我解决这个问题
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)