【问题标题】:How to create node.js html server with css如何使用 css 创建 node.js html 服务器
【发布时间】:2020-11-22 16:22:42
【问题描述】:

我正在尝试使用 http 和 express 为 html 创建简单的 node.js 服务器

它工作正常,但 css 不显示

这是我的服务器的代码

const express = require("express");
const app = express();

app.use(express.static("css"));

var router = express.Router()

app.use('/',router)

router.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.htm")
})

app.listen(8080)

以及我的服务器的代码,使用 http 创建的代码

const http = require("http")
const port = 8080
const fs = require('fs')

const server = http.createServer(function(req,res) {
    fs.readFile('./index.html', (error, data) => {
        if(error) {
            res.writeHead("404")
              res.write("Error. File not found.")
        } else {
            res.use
            res.write(data)
        }
        res.end();
    })

})

server.listen(port, function(error) {
    if(error) {
        console.log(error)
    } else {
        console.log("server is listening on port " + port)
    }
})

我所有的html代码

<!DOCTYPE html>
<html lang="en">
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Domodinak</title>
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>
        <p>Hello world</p>
    </body>
</html>

还有css

body {
    background-color: deeppink;
}

如果你知道如何帮助我,请帮助:)

【问题讨论】:

    标签: html css node.js http server


    【解决方案1】:

    确保您正确寻址css 文件夹。这取决于您的项目文件夹结构。建议将静态文件保存在名为public 的文件夹中,然后将文件保存在单独的文件夹中,例如jscss。例如,我假设您有一个 src 文件夹,这是您的快速服务器文件的目录,另一个文件夹在 src 文件夹旁边,您有一个 public 文件夹和 css 子文件夹。 将样式表文件放在css 子文件夹中,将html 文件放在public 文件夹中,然后将代码更改为:

    const express = require("express");
    const path = require("path");
    const app = express();
    
    app.use(express.static(path.join(__dirname, "../public")));
    
    // var router = express.Router()
    
    // app.use('/',router)
    
    // router.get("/", (req, res) => {
    //  res.sendFile(__dirname + "/index.htm")
    // })
    
    app.listen(8080)
    

    您的项目结构应如下所示:

    |-public -| css -| style.css
              index.html
    |-src -| app.js
    

    运行服务器文件,然后使用localhost:8080 检查您的浏览器。它从您之前传递给表达的静态目录中提供index.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 2023-02-06
      相关资源
      最近更新 更多