Express res.download()

时间:2018-09-18 17:16:00

标签: javascript reactjs express

我不知道为什么会这样,但这确实很烦人。我希望根据express docs下载文件。我有下一个代码:

  //in react (App.js)
  download = () => {
    const { images, target } = this.state;
    const filename = images.find(img => img.id === target).filename;
    fetch('http://localhost:3001/download', {
      method: 'post',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({filename})
    })
  }
  //in express (server.js)
  app.post('/download', (req, res) => {
    var file = '../public/images/' + req.body.filename;
    res.download(file, req.body.filename);
  });

文件夹结构:

  -server
    |-server.js
  -public
    |-images
      |-a.jpg
      |-b.jpg
  -src
    |-App.js

什么都没有发生,错误未显示。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

我认为您遇到的问题是您使用的是HTTP POST而不是HTTP GET

答案 1 :(得分:2)

这是一个挑战,但这对我有用。

let express = require('express'),
path = require('path'),
port = process.env.PORT || process.argv[2] || 8080,
app = express();

app.get('/', (req, res)=>{

res.send('<a href="/download">Download</a>');

});

app.get('/download', (req, res)=>{

res.download(path.join(__dirname, 'views/files.pug'), (err)=>{

    console.log(err);

});
console.log('Your file has been downloaded!')
});

app.listen(port, ()=>{

console.log('res is up on port: ' + port);

});
``

只需用您的文件名替换即可。

相关问题