0

My application is written with ReactJs on the client side and NodeJs express on the server side. When I try to get an .ico file and display it on the client side using this code:

Client side:

async function getIcon() {
    try {
        const res = await axios.get(`${BASE_URL}/file/icon`);
        const blob = res.blob()
        return blob
    } catch (error) {
        return error
    }
}

Server side:

router.get('file/icon/', (req, res) => {
    try {
        const pathToIcon = path.join(${APP_DIR}, 'public', 'icon', 'my-icon-file.ico')
        const file = fs.readFileSync(pathToIcon)
        res.setHeader('Content-Type', 'image/x-icon')
        res.setHeader('Content-Disposition', 'attachment; filename=filename.ico')
        res.send(file)
    } catch (error) {
        res.status(400).send("Problem to get .ico file")

    }
})

I get this error:

TypeError: res.blob is not a function. For some reason res is of type string and includes many chars.

How do I solve this problem in such a way that res will include the 'blob' method.

I also tried (on the client side):

async function getIcon() {
    try {
        const res = await axios.get(`${BASE_URL}/file/icon`,{responseType: 'blob'});
        const blob = res.blob()
        return blob 
    } catch (error) {
        return error
    }
}

But it doesn't work.

  • 1
    You cannot use the api's of fetch and axios for the same api call, choose one and use that one – Ferrybig Apr 02 '23 at 12:21
  • Does this answer your question? [node.js axios download file stream and writeFile](https://stackoverflow.com/questions/55374755/node-js-axios-download-file-stream-and-writefile) – Konrad Apr 02 '23 at 22:07

1 Answers1

0

There's no need for res.blob unless it's absolutely necessary, so you can just use res.text instead and set the headers.

So... if you REALLY need to use a blob for your purposes:

router.get('file/icon/', (req, res) => {
    try {
        const pathToIcon = path.join(${APP_DIR}, 'public', 'icon', 'my-icon-file.ico')
        const file = fs.readFileSync(pathToIcon)
        res.setHeader('Content-Type', 'image/x-icon')
        res.setHeader('Content-Disposition', 'attachment; filename=filename.ico');
        var blobbed = new Blob([file], [type: 'image/x-icon'])
        res.send(blobbed)
    } catch (error) {
        res.status(400).send("Problem to get .ico file")

    }
})
Also, I have not personally tested any of this, but if you encounter any errors feel free to let me know.
Oris Sin
  • 1,023
  • 1
  • 13
  • 33