express: how to send html together with css using sendFile?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 08:52:28

问题


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?


回答1:


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");
});

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));

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.

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"));

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



来源:https://stackoverflow.com/questions/38757235/express-how-to-send-html-together-with-css-using-sendfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!