Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

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

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

app.get('/', function(req, res) {
  res.sendFile(__dirname + "/" + "index.html");
});
<link rel="stylesheet" href="style.css">
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...