如何使用 req.params 和 join 方法在快递中发送文件



我正在使用路由参数在express.js中创建路由。我想要一个firstCase参数的 url example.com/case/firstCase

但是,我不知道如何将发送文件与params一起使用。我想做的是附加.html但我认为它不起作用,因为该方法join逗号分隔的每个元素之间添加/。换句话说,路径将是views/statics/case/firstCase/.html

这是我在服务器.js中的代码。

const express = require('express')
const app = express()
const path = require('path')
// no need to use app.use(app.router) because of that update
// function signature express.static(root, [options])
app.use(express.static('public'));
// mount root to views/statics
app.use('/', express.static('views/statics'));
const PORT = process.env.PORT || 3000;
app.listen(PORT,() => {
    console.log(`Server is listening on port ${PORT}`)
  });
app.get('/case',(req,res,next)=> {
  res.sendFile('case.html', { root: path.join( __dirname, 'views/statics')})
})

app.get('/case/:case',(req, res)=>{
  res.sendFile(path.join(__dirname, 'views/statics/case', req.params.case + '.html'));
}))

如上所述的讨论,您不使用view engine

添加view engine喜欢

  1. 哈巴狗链接
  2. Ejs 链接

最新更新