【问题标题】:Node.js can't get css file [duplicate]Node.js 无法获取 css 文件 [重复]
【发布时间】:2018-07-17 10:24:44
【问题描述】:

我想通过 Node.js localhost 获取 css 文件。 index.php 加载正确,style.css 无法加载。

我的结构文件

app.js views
     index.php
     css
        style.css

我的 app.js

const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

fs.readFile('views/index.php', (err, html) => {
    if (err) {
        throw err;
    }

    const server = http.createServer((req, res) => {
        res.statusCode = 200;
        res.setHeader('Content-type', 'text/html');
        res.write(html);
        res.end();
    });

    server.listen(port, hostname, () => {
        console.log('Server started on port ' + port + (Date.now()));
        console.log('address ' + hostname);
    });
});

我的 index.php

<html>
    <head>
        <link rel="stylesheet" href="css/style.css" />
        <title>title</title>
    </head>
</html>

【问题讨论】:

  • 您的服务器在每次响应时都将 html 文件提供给客户端,这就是您的样式无法加载的原因。

标签: php html css node.js


【解决方案1】:

如果你想使用 php,也许你应该考虑在服务器上使用 js 以外的东西。有 MAMP 等包。未加载 css 的原因是您只有一种方式可以访问您的服务器,并且会呈现您的索引文件。

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 2013-07-06
    • 2018-05-30
    • 2013-08-09
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 2013-12-18
    相关资源
    最近更新 更多