我不知道为什么会这样,但这真的很烦人。我期望根据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什么都没有发生,错误没有显示。有什么想法吗?
发布于 2018-09-19 01:22:44
我认为您遇到的问题是您正在使用HTTP POST而不是HTTP GET
发布于 2018-09-19 02:02:15
这是一个挑战,但这对我来说很管用。
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);
});
``只需将文件名替换为您的文件名即可。
https://stackoverflow.com/questions/52391627
复制相似问题