Html express:如何使用sendFile 将html 和css 一起发送?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38757235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
express: how to send html together with css using sendFile?
提问by neolicd
var app = require('express')();
app.get('/', function(req, res) {
res.sendFile(__dirname + "/" + "index.html");
});
<link rel="stylesheet" href="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?
我使用上面的 node.js 代码发送一个 html 文件。要格式化 html 文件,我需要发送另一个 css 文件(style.css)。
我的问题是:如何使用 sendFile() 发送这两个文件(index.html 和 style.css)并将它们集成到客户端?
回答by Explosion Pills
The browser should load style.css
on its own, so you can serve that as a route:
浏览器应style.css
自行加载,因此您可以将其作为路由使用:
app.get('/style.css', function(req, res) {
res.sendFile(__dirname + "/" + "style.css");
});
However, this would get very cumbersome very quickly as you add more files. Express provides a built in way to serve static files:
但是,随着您添加更多文件,这会很快变得非常麻烦。Express 提供了一种内置方式来提供静态文件:
https://expressjs.com/en/starter/static-files.html
https://expressjs.com/en/starter/static-files.html
const express = require("express");
const app = express();
app.use(express.static(__dirname));
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
与您的服务器代码在同一目录中,您还将服务器代码作为静态文件提供,这是不可取的。
Instead you should move index.html
, your css, images, scripts, etc. to a subdirectory such as one named public
and use:
相反,您应该将index.html
您的 css、图像、脚本等移动到一个子目录,例如一个名为public
和使用的子目录:
app.use(express.static("public"));
If you do this, Express will serve index.html
automatically and you can remove your app.get("/"
as well.
如果您这样做,Express 将index.html
自动提供服务,您也可以删除您的app.get("/"
。