使用Node.js和Express渲染HTML页面时的路径问题
用Express渲染HTML页面的路径问题及解决方法
问题场景
尝试使用Express渲染HTML文档,编写的初始代码如下:
import { URL } from 'url' const __dirname = decodeURI(new URL('.', import.meta.url)) import express from 'express' const app = express() const port = 3000 import { join } from 'path' const basePath = join(__dirname, 'templates') //testing the output console.log('__dirname:', __dirname) console.log('basePath:',basePath) app.get('/', (req, res) => { // res.sendFile(`${__dirname}/index.html`) // res.sendFile(`${basePath}/index.html`) // res.sendFile('index.html',{root:basePath}) res.send(__dirname + '/templates/index.html'); }) app.listen(port, () => { console.log(`App running in port:${port}`) })
预期渲染的HTML内容
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Home</title> </head> <body> <h1>Home Express!</h1> </body> </html>
遇到的问题
实际返回异常页面,尝试app.get中的多条注释代码均未解决问题。调试过程中:
- 执行
res.send(join(__dirname, 'templates', 'index.html'))输出路径为file:\D:\Curso_Node\6_EXPRESS\3_render_html\templates\index.html - 执行
res.sendFile(join(__dirname, 'templates','index.html'))时触发报错:TypeError: path must be absolute or specify root to res.sendFile
解决方法
通过process.cwd()拼接路径的方案解决问题,可行代码如下:
import { URL } from 'url' const __dirname = decodeURI(new URL('.', import.meta.url)) import express from 'express' const app = express() const port = 3000 import { join } from 'path' app.get('/', (req, res) => { res.sendFile(join(process.cwd(), 'templates', 'index.html')) }) app.listen(port, () => { console.log(`App running in port:${port}`) })
内容的提问来源于stack exchange,提问作者Gi_Developer
相关产品推荐
相关产品推荐

