Why is html page sent by express.js route not connected to a css stylesheet?

115
April 29, 2019, at 11:50 AM

So I have server.js file that imports a router

const path = require("path");
const express = require("express");
const app = express();
const PORT = 8080;
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(require('./app/routing/htmlRoutes')); 

The router looks like this

const path = require("path");
var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
    res.sendFile('home.html', { root: path.join(__dirname, '../public') });
});
router.get('/survey', function(req, res) {
    res.sendFile('survey.html', { root: path.join(__dirname, '../public') });
});

module.exports = router;

It does work! It renders html pages, however those html pages have css stylesheets hooked up to them and located in the same directory, but they render as blank html sheets (unstyled)... How do I make them render with css stylesheets taken into account?

Answer 1

When the browser encounters the style reference of the loaded html file, it tries to load the file specified in the src attribute. Now your server script doesn't have a route for that. It will load the css if you add a route for that specific css file. However as Irshad said, the standard way to do this is to add a route for all the static files.

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

Right now, you are only sending home.html everytim the root is requested.

Change your code to read the requested file from the req and serve that file whatever it may be.

Answer 2

Why not set the middleware to serve static files (css, html) from public folder app.use(express.static("public"))

See the working example

Rent Charter Buses Company
READ ALSO
ESP8266 / Arduino modbus RTU Buffer data conversion

ESP8266 / Arduino modbus RTU Buffer data conversion

I am using ESP8266 and ModbusMasterh library to communicate with RS485 enabled power meter

135
Easy to implement payment gateway that works in Pakistan?

Easy to implement payment gateway that works in Pakistan?

I am a beginner in front end development and I need help regarding payment gateway easiest to implement

128
How to set an Alarm Using an Intent Selecting the full date of the alarm (including day, month)

How to set an Alarm Using an Intent Selecting the full date of the alarm (including day, month)

So I'm trying to add a feature in my app to launch the alarm clock and set one, I tried it using the usual code:

143
New java implementation for the new subscription API for PayPal [on hold]

New java implementation for the new subscription API for PayPal [on hold]

I want to integrate with paypal for recurring payments project, i noticed in the API docs the following :

133