[Node.js] Trigger a File Download in Express

Downloading and saving a file is a common scenario when building out your web application. Using Express, you can either trigger a download from an existing file or set the headers on the response to send a file you created through Node. This lesson walks you through both approaches.

If the file is already exists on the server:

const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.download('./test.txt');
})

If files is not there:

app.get("/", (req, res) => {
  res.setHeader(
    "Content-disposition",
    "attachment; filename=message.json"
  )
  res.setHeader("Content-type", "application/json")
  res.send(JSON.stringify({message: "Hello"}))
})
原文地址:https://www.cnblogs.com/Answer1215/p/9927046.html