环境需在项目建一个public文件夹以及public文件夹下面有一个text.txt文件。在linux系统下测试了这个demo可以正常运行。
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello world");
});
app.all("*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", " 3.2.1");
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.use("/public", express.static("./public"));
app.use("/test/download",(req,res,next)=>{
const fs = require('fs')
const fileName = 'test.txt'
const filePath = __dirname + '/public/test.txt'
if(!fs.existsSync(filePath)){
return res.send({
code:"1",message:"test.txt is not exist"})
}
res.status(200).download(filePath,fileName,(err)=>{
if(err){
res.send({
code:"1",message:"server err"})
}
})
})
app.listen(4568, (req, res) => {
console.log(res);
console.log("Server is running at http://localhost:4568");
});
前端请求接口 http://localhost:4568/test/download