-1

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

Ali
  • 17
  • 2
  • is there a specific security requirement? if not why not just use a hyperlink? with target set to blank? – jidexl21 May 30 '22 at 18:30
  • How can i use hyperlink – Ali May 30 '22 at 18:35
  • You're handling `app.get("/",` to start the download, but you need a different route than that of your index file. Also, to start the download of the file client-side, all you need is `location.href = url_of_file;` or simply `download` –  May 30 '22 at 18:37

1 Answers1

0

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.

Krytech
  • 71
  • 5