我的nodejs后端使用http-server在localhost:8080上运行,前端在localhost:8081上运行,我无法将文件从服务器端下载到客户端,我是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);
})
前端响应:- 我从服务器成功获得响应,但未下载文件。
这个你能帮我吗