【问题标题】:How to show html file with css in local server [duplicate]如何在本地服务器中显示带有css的html文件[重复]
【发布时间】:2022-01-05 12:59:43
【问题描述】:

当我在用 node.js 编写的本地服务器上运行我的 HTML 文件时,我在 HMTL 文件中链接的 CSS 文件不起作用。

我的 javascript 代码

const http=require('http');
const fs=require('fs');
http.createServer(function(req,res){
    fs.readFile("index.html",(error,data)=>{
        res.writeHead(200,{'Content-Type':'text/html'});
        res.write(data);
        return res.end();
    })

}).listen(8080);

我的 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">
    <link rel="stylesheet" type=text/css href="./css/desktop.css">
    <title>CODESTER-TrackYourProgress</title>
</head>
<body>
...
</body>
</html>

我的 CSS 文件位于 css 文件夹中,名称为 desktop.css

【问题讨论】:

  • 你试过 fs.readFile('./index.html', ... ) 吗??
  • 您的网络服务器使用 HTML 文件的内容响应每个请求。您没有编写任何除此之外的任何代码,所以这是唯一正在发生的事情。您需要查看req 变量并根据请求包含的内容向浏览器提供不同的文件。

标签: node.js webserver


【解决方案1】:

你可以试试这样的:

const http=require('http');
const fs=require('fs');
http.createServer(function(req,res){
    const { method, url } = req;
    const surl = new URL(url, 'url the server is running on');
    if (method == 'GET' && surl.pathname == '/index.html') {
        fs.readFile("index.html",(error,data)=>{
            res.writeHead(200,{'Content-Type':'text/html'});
            res.write(data);
            return res.end();
        })
    }
    if (method == 'GET' && surl.pathname == '/css/desktop.css') {
        fs.readFile("/path/to/css/desktop.css",(error,data)=>{
            res.writeHead(200,{'Content-Type':'text/css'});
            res.write(data);
            return res.end();
        })
    }

}).listen(8080);

请务必将/path/to/css/desktop.css 替换为文件的实际路径,并将'url the server is running on' 替换为服务器正在运行的有效网址,例如。 http://127.0.0.1/

【讨论】:

  • 这段代码抛出了引用错误
  • ReferenceError: 方法未定义
  • @Vivek 已编辑:现在应该可以使用
【解决方案2】:

Express 模块解决了问题 你可以使用

const express = require('express');
const app = express();
app.use(express.static('folder containing your static files'));
//statics files are css,photos etc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    相关资源
    最近更新 更多