I am working in a fullstack project I have backend folder using nodejs with server.js file of the following code
const express = require("express");
const cors = require("cors");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname, "puplic/uploads")));
app.use(cors());
app.get("/", async (req, res) => {
res.download("b.rar");
});
app.listen(3000, () => {
console.log("server connected");
console.log(path.join(__dirname, "puplic/uploads"));
});
and client side of index.html of the following code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">press</button>
<script src="index.js">
</script>
</body>
</html>
and client side index.js of the following code
let btn=document.getElementById("btn")
btn.onclick=()=>{
fetch("http://localhost:3000/",{
method:"GET",
mode:"cors"
}).then(res=>
{
}
)
}
how i can fetch the server side and download the file in the client pc when the client press the button
I would recomment to redirect to a blank page and set a download header there.
Client side would look like this:
let btn=document.getElementById("btn")
btn.onclick=()=>{
window.open("http://localhost:3000/", '_blank')
}
on the serverside you have to set a download header, code would look like this:
app.get("/", async (req, res) => {
res.download("b.rar");
});
optional you can set the headers by yourself using:
app.get("/", async(req, res) =>.{
res.set({
"Content-Disposition": "attachment; filename=\"b.rar\"",
"Content-Type": "application/x-rar-compressed, application/octet-stream"
});
const fs = require('fs/promise');
fs.readfile('./b.rar').then(file => {
res.send(file);
})
});
I havent tested this whole stuff but maybe it can help you. Optional it is enough to use an tag instead of a button and manage the redirection there since some browsers deny window.open from javascript due to cross site injection.