Shine
Shine

Reputation: 67

Axios doesn't not receiving the header I set

I deploy the Server.cjs file on the server side:

var express = require('express');
var cors = require('cors');
var app = express()
app.use(express.urlencoded({ extended: true }))
const port = 3001;
app.use(cors())

app.get("/download", (req, res) =>{
    const file_uniquename = req.query.file_uniquename
    const { file_originalname, mimetype, filepath } = ...

    res.setHeader('Content-disposition', 'attachment; filename=' +  file_originalname)
    res.setHeader('Contect-type', mimetype)
    const stream = fs.createReadStream(filepath)
    stream.pipe(res)
  }
})


app.listen(port, () => {console.log(`App listening at :${port}`);});

I am trying to use axios to receive file streams and filenames on the front end, I see the headers I set in the network tab in developer tools, but the res received by axios has empty headers. Why?

//import fileDownload from 'js-file-download'

axios.get(serverurl + 'download', { params: { file_uniquename: file_uniquename }})
    .then(res => {
        //fileDownload(res.data)
        //console.log(res.headers['Content-disposition'])
        console.log(res.headers)
    });

Upvotes: 0

Views: 3671

Answers (1)

Shine
Shine

Reputation: 67

Thanks for the Nick Uraltsev's answer at "Axios get access to response header fields", and the comment of Old Man Walter.

  • Because of cors, only some of the headers will be accessed by the browser. So we should use Access-Control-Expose-Headers to make the browser access the other headers.
    res.setHeader("Access-Control-Expose-Headers", "X-Suggested-Filename");
    res.setHeader("X-Suggested-Filename", originalname);

    fs.createReadStream(filepath).pipe(res)
  • In addition, the spelling of Contect-type is wrong, which should be Content-Type, which should not be seen as a big problem.

Upvotes: 2

Related Questions