微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法从我的 node js 服务器下载文件我的后端和前端是解耦的

如何解决无法从我的 node js 服务器下载文件我的后端和前端是解耦的

我的 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);
  })

前端响应:- 我收到了服务器的成功响应,但没有下载文件

enter image description here

请帮我解决这个问题

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。