Expressフレームワークはダウンロードファイルインターフェイスを記述し、フロントエンドはファイルのバイナリ形式を取得できます

環境では、プロジェクトにパブリックフォルダーを作成し、パブリックフォルダーの下にtext.txtファイルを作成する必要があります。このデモは、Linuxシステムで正常に実行できます。

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

おすすめ

転載: blog.csdn.net/qq_26889291/article/details/109357460