我想發送 html 檔案作為回應,express這樣做我需要給出位置或path檔案index.html。
所以這是我的檔案結構 -
MyWebsite
Html
index.html
Css
index.css
Js
index.js
如果您仍然不了解檔案結構,請查看檔案結構的影像:

所以在我的 JavaScript 中我寫了這樣的東西:
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const port = process.env.port || 8080;
app.get('/', (req, res) => {
const htmlFile = path.join(__dirname, '/index.html');
res.sendFile(htmlFile)
});
app.listen(port);
給出錯誤 -
Error: ENOENT: no such file or directory, stat 'F:\Websites\MyWebsite\js\index.html'
它不作業!我無法提供路徑或檔案夾名稱!如何獲取index.html檔案夾的路徑
任何幫助將不勝感激!
uj5u.com熱心網友回復:
它很簡單,您已經設定了 back-word,因此服務器可以找到您 index.html 將您的代碼更改為
app.get('/', (req, res) => {
const htmlFile = path.join(__dirname, '/index.html');
res.sendFile(htmlFile)
});
新代碼將是
app.get('/', (req, res) => {
const htmlFile = path.join(__dirname, '../html/index.html');
res.sendFile(htmlFile)
});
我希望它對你有用,它對我有用
uj5u.com熱心網友回復:
您可以使用“路徑”模塊將一個目錄移回。
path.join(__filename, '..', 'html', 'index.html')
這樣,您將在不同的作業系統中運行您的應用程式時避免斜線并消除問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447591.html
標籤:javascript 节点.js 表示 小路
上一篇:如何在一個函式中呼叫多個ID?
