简体   繁体   中英

NodeJS/React install xpi file instead of downloading it

Situation:

1.My nodeJS server serves a file like so:

fileRouter.get('/firefox',  async (req,res)=>{
        const mime = 'application/x-xpinstall'
        fs.readFile('controllers/file.xpi', (err, data)=>{
                if(err){
                        res.writeHead(500, {'Content-Type' : 'text-plain'})
                        return res.end('error while downloading the file')
                }
                res.writeHead(200, {'Content-Type' : mime})
                res.end(data)
        }
        )
 

})

2.My react app downloads it like so:

const handleDownload = async (e) =>{
    const res = await axios({
        url:'/api/download/firefox',
        method:'GET',
        responseType:'blob'
    })
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const link = document.createElement('a')
    link.href = url
    document.body.appendChild(link)
    link.click()
}

Problem:

I expected the xpi extension file to be installed by firefox instead of being downloaded. I thought setting the mime type in my node server would lead to such behaviour from firefox.

InstallTrigger is deprecated and isn't mentionned in mozilla documentation.

I think the problem lies in the frontend code: what should I change? (I'm not even satisfied with the way downloading is implemented, I must miss something there)

Thanks for your help.

Solution:

Both the backend and frontend code needed to be reworked; The solution is clearly simple.

1.BACKEND:

The fileRouter Route is no more necessary. Express is used. Targeted file is in a public/ directory created at the root of the backend directory.

app.js:

express.static.mime.define({'application/x-xpinstall' : ['xpi']})
app.use('/download' , express.static('public'))


2. FRONTEND:

Long story short: declare your component then the solution is only HTML really...

const Download = () =>{
return(
    <a href='https://yourwebsite.com/download/yourfirefoxextension.xpi'>
        download the extension
    </a>
)
}

Postscript:

The extension is directly installed by firefox after the user accepts it. No need for setting-up an express.Router(). I'm still curious to know if the first way I tried had any chance to work (if you feel you have the answer, don't hesitate).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM