res.download不会提示文件下载,但会在文件夹中打印文件。路由问题

时间:2019-05-12 21:57:22

标签: node.js express handlebars.js

我正在尝试通过单击按钮为node.js开发文件下载功能。当我单击客户端上的按钮时,文件下载到服务器文件夹,但客户端没有提示文件下载。如果我直接转到路由域/ excel,它将执行我想要的操作,但是,如果我从家里转到/ excel,它将文件放在服务器公用文件夹中,但不再为客户端下载。我在做什么错了?

--/routes/excel.js
var express = require('express');
var router = express.Router();
const Json2csvParser = require('json2csv').Parser;
var fs = require('fs');

const fields = ['car', 'price', 'color'];
const myCars = [{
  "car": "Audi",
  "price": 40000,
  "color": "blue"
}, {
  "car": "BMW",
  "price": 35000,
  "color": "black"
}, {
  "car": "Porsche",
  "price": 60000,
  "color": "green"
}];

const json2csvParser = new Json2csvParser({
  fields
});
const csv = json2csvParser.parse(myCars);

router.get('/', function(req, res, next) {

  var path = './public/file' + Date.now() + '.csv';
  fs.writeFile(path, csv, function(err, data) {
    res.download(path); // This is what you need
  });
});

module.exports = router;

--views/home.handlebars  
$('#go').on("click", () => {
  $.get("/excel");
});

--routes / index.js
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('home', {
    title: 'Express'
  });
});

0 个答案:

没有答案