簡體   English   中英

Node.js提供html文件

[英]Node.js serve html files

我有這樣的目錄結構:

    server
       code
         app.js
         web
           html
               index.html
           css
               index.css
           scripts
               index.js

我的app.js代碼正在嘗試提供html文件index.html,但顯示錯誤,這是該代碼:

    app.get('/web',function(req,res) 
    {
        res.sendFile('../web/html/index.html');
    })

傳遞給sendFile()並使它正常工作的路徑是什么,以便html文件在運行時也可以找到腳本文件和css?

我是node.js的新手。

您可以使用express.static("")來提供靜態文件。 例:

const express = require("express");
const app = express();
const server = app.listen(PORT, () => {});
app.use(express.static("./web"));

這將使Web文件夾中的所有內容公開,並且可以在localhost:PORT/html/index.html上找到index.html文件。這還將正確地為您的jscss文件提供服務

要單獨提供html,您將需要使用絕對路徑:

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

記住要包含const path = require(path)

暫無
暫無

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

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