You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 14:37:32