【问题标题】:express: how to send html together with css using sendFile?express:如何使用 sendFile 将 html 和 css 一起发送?
【发布时间】:2016-12-09 23:31:46
【问题描述】:

var app = require('express')();

app.get('/', function(req, res) {
  res.sendFile(__dirname + "/" + "index.html");
});
<link rel="stylesheet" href="style.css">

我使用上面的 node.js 代码来发送一个 html 文件。要格式化 html 文件,我需要发送另一个 css 文件(style.css)。
我的问题是:如何使用 sendFile() 发送这两个文件(index.html 和 style.css)并将它们集成到客户端?

【问题讨论】:

    标签: html css node.js express sendfile


    【解决方案1】:

    浏览器应自行加载style.css,因此您可以将其用作路由:

    app.get('/style.css', function(req, res) {
      res.sendFile(__dirname + "/" + "style.css");
    });
    

    但是,当您添加更多文件时,这会很快变得非常麻烦。 Express 提供了一种内置方式来提供静态文件:

    https://expressjs.com/en/starter/static-files.html

    const express = require("express");
    const app = express();
    app.use(express.static(__dirname));
    

    请记住,如果index.html 与您的服务器代码位于同一目录中,您也会将服务器代码作为静态文件提供,这是不可取的。

    您应该将index.html、您的css、图像、脚本等移动到一个子目录,例如一个名为public 的子目录,然后使用:

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

    如果您这样做,Express 将自动提供 index.html,您也可以删除您的 app.get("/"

    【讨论】:

    • 太棒了!顺便说一句,浏览器会因为以下代码而加载 style.css 吗?
    • 是的,可能值得您研究一些 HTML 内容以直接跳转到节点内容。
    • @Explosion Pills :如果您尝试使用邮递员来解决这个问题,它只会返回您的 html
    • @ShashankGaurav 我对你的问题感到困惑;你想用 Postman 做什么?
    • 我删除了将所有文件添加到文件夹中的所有内容,添加了app.use(express.static("folderName"));,并且繁荣在根/ url 中工作。谢谢!
    猜你喜欢
    • 2018-08-26
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 2018-06-16
    相关资源
    最近更新 更多