首页 > 解决方案 > 如何使用 req.params 和 join 方法快速发送文件?

问题描述

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

但是,我不知道如何将 sendFile 与params. 我想做的是追加.html,但我认为它不起作用,因为方法joinadd/在每个元素之间用逗号分隔。换句话说,路径将是views/statics/case/firstCase/.html

这是我在 server.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'));
}))

标签: node.jsexpress

解决方案


如上所述,您没有使用view engine.

添加view engine喜欢

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

推荐阅读