My nodejs backend is running on localhost:8080 and frontend on localhost:8081 using http-server, I am not able to download file from my server side to client side, I am new to node js so facing some problems with it
What I tried
I created a readstream to my required file on server side and then pipe it to res object , also I set some headers :-
res.setHeader("Content-Type","image/png") // as I am trying to download a
res.setHeader("Content-Disposition", `inline; filename=${filename}`);
But it still fails
Code:-
code for downloading a file from server side
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 code:-
const cors = require("cors");
app.use(cors({
origin: "http://localhost:8081",
credentials: true,
withCredentials: true
}))
frontend code:-
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);
})
Response on frontend:- I got successfully response from server but file isn't downloaded.
please help me out with this