簡體   English   中英

如何從高於我的服務器文件夾級別的目錄在 Express 中提供 HTML 文件?

[英]How do I serve an HTML file in Express from a directory which is a level above my server folder?

我正在嘗試通過更深一層的 Express 服務器提供位於我的主目錄中的 HTML 文件:在我的服務器文件夾中。 這是服務器代碼的設置方式:

 const express = require('express'); const app = express(); app.use(express.json()); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }) const port = 5000; app.listen(port, () => console.log(`Server is listening on port ${port}.`))

我收到的錯誤是:

Error: ENOENT: no such file or directory, stat '/mnt/c/Project-Directory/server/index.html'

從這個錯誤中可以清楚地看出為什么我無法訪問我的 HTML 文件; 我的服務器存在於 /server 文件夾中,我的 index.html 文件存在於 Project-Directory 文件夾中。 但是,我不確定如何訪問當前目錄中的 HTML 文件。

您可以使用path.join並指定要返回一個目錄( ../ ):

const path = require('path');


app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '../index.html'));
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM