表达:如何使用sendFile将HTML和CSS一起发送? [英] express: how to send html together with css using sendFile?

查看:83
本文介绍了表达:如何使用sendFile将HTML和CSS一起发送?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)并将它们集成到客户端?

I used the above node.js code to send a html file. To get the html file formatted I need to send another css file(style.css).
My question is: how can I send both of these two files(index.html and style.css) using sendFile() and integrate them together in the client side?

推荐答案

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

The browser should load style.css on its own, so you can serve that as a route:

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

但是,随着您添加更多文件,这将变得非常麻烦. Express提供了一种内置的方式来处理静态文件:

However, this would get very cumbersome very quickly as you add more files. Express provides a built in way to serve static files:

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

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

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

Keep in mind that if index.html is in the same directory as your server code you will also serve the server code as static files which is undesirable.

相反,您应该将index.html,您的css,图像,脚本等移动到一个名为public的子目录中,并使用:

Instead you should move index.html, your css, images, scripts, etc. to a subdirectory such as one named public and use:

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

如果执行此操作,Express将自动提供index.html,并且您也可以删除app.get("/".

If you do this, Express will serve index.html automatically and you can remove your app.get("/" as well.

这篇关于表达:如何使用sendFile将HTML和CSS一起发送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆