Incorporate a static CSS file using Express.js

I'm facing an issue with my .css file that was generated using Koala from a .scss file and added to my index.html. Unfortunately, the page is not serving my file because I forgot to add it as static on my Express server. I have tried following the various options listed in the Express server documentation http://expressjs.com/es/starter/static-files.html:

1)

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

However, I used:

app.use(express.static('styles/css'));

2)

app.use('/static', express.static('public'));

But I ended up using:

app.use('/static', express.static('styles/css'));

3)

app.use('/static', express.static(__dirname + 'public'));

Instead, I used:

app.use('/static', express.static(__dirname + '/styles/css'));

Unfortunately, none of these methods seem to be working for me despite trying different combinations. It's clear that I must be doing something wrong.

This is the structure of my folders:

project
  src
   styles
      bower_components
      css
         app.css
      sass
         app.sass
   app.js
   index.html
  package.json
  server.js
  webpack.config.js

Here is a snippet of my express server.js file:

const path = require('path');
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const config = require('./webpack.config');

const app = express();
const compiler = webpack(config);
const middleware = webpackDevMiddleware(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath,
  stats: { colors: true },
});

app.use(middleware);
app.use(webpackHotMiddleware(compiler));

app.get('*', (req, res) => {
  const renderHtml = () => middleware.fileSystem
    .readFileSync(path.join(compiler.outputPath, 'index.html'))
    .toString();
  res.send(renderHtml());
});

app.use('/static', express.static(path.join(__dirname, '/styles/css')))

app.listen(3000, '0.0.0.0', function (err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://0.0.0.0:3000');
});

I would appreciate any guidance on how to correctly use the express static line in this scenario. What am I missing or doing incorrectly? Thank you for your help in advance.

Answer №1

It seems like the issue might be with your app.get('*' ...). This wildcard matches every possible URL, which could be causing a conflict.

If you have app.use('/static', ...) after that, it might be getting ignored.

Here are a couple of suggestions:

  • Try moving app.static(...) before app.get('*', ...).
  • If you're using
    app.static('/static', express.static(path.join(__dirname, '/styles/css')))
    , make sure your HTML <link> tag looks like this:
    <link rel='stylesheet' href='/static/your-css-file.css' type='text/css'>
  • Alternatively, you can simply use
    app.use(express.static(__dirname))
    and update your HTML to include:
    <link rel='stylesheet' href='/styles/css/your-css-file.css' type='text/css'>

Remember, the order in which you declare your middlewares with app.use(...) is important.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Variable Stores the Results of Node.js http.request

Hello everyone, I've been working on a project where I need to pass the results from an https.request in my node.js code to a variable. The https.request is set up to communicate with a SOAP API and receive the response successfully. My main objectiv ...

Display three images with titles in a row using CSS

I'm trying to align 3 figures with captions horizontally in the middle of the page, side by side, but so far I've only been able to do it vertically. How can I achieve this using just HTML5 and CSS? This is my current HTML: <div class="r ...

`Nginx with a touch of material design`

Currently, I'm in the process of implementing material design UI on a functioning web application. The application utilizes Nginx, PHP, and PostgreSQL. While I have proficiency in PHP and PostgreSQL to ensure the functionality (code composed in notepa ...

`Is it possible to renew the Refresh Token and Access Token while making a Resource Request?`

As I delve into implementing JWT Tokens, including both Access tokens and Refresh tokens, a particular challenge has arisen. Specifically, when attempting to request a protected resource with an expired access token, while the refresh token remains valid. ...

The server has failed to start

The server code below is not currently in operation: import express from 'express'; import mongodb from 'mongodb'; const app = express(); const dburl = 'mogodb://localhost/crudwithredux'; mongodb.MongoClient.connect(dburl, ...

What is the best way to transform height in pixels to percentage in order to create a responsive design that adjusts smoothly on

Currently, I am in the process of developing a responsive grid system by using a max-width of 980px to convert my fixed PX widths to percentages. However, I am facing some challenges in updating the heights that are also set in PX to %. Could anyone provid ...

Unable to transmit cookie to the response when the user is on Safari/iOS

When setting up a web server using Node.js and Express.js, I am adding cookies to the response res.cookie('token', token, { httpOnly: true, expires: new Date(Date.now() + sixMonths), secure: true, sameSite: 'none', s ...

When the parent element is centered, align the children to the left

Can children be aligned to the left when the parent is aligned to the center? I have a list of elements where the parent block should be centered, but the children need to align to the left. https://i.sstatic.net/ixRxQ.jpg Now I found a solution to alig ...

javascript regular expression

Is there a way to extract the text that falls between the first colon and the first period in a string? s:4332Hhj4j32hh432kjh.EF4324rf46543DSVC3443 I attempted using the following regex: /:(.*?)\./g Unfortunately, it still captures the colon and p ...

Tips for adjusting text placement on a Bootstrap responsive webpage:

Hey there, I hope everything is going well. I'm facing a little issue here. I'm trying to design a page layout that looks like this: Image - Description Description - Image Image - Description and so on... However, when viewed on a smaller devi ...

leveraging the power of Node.js Express for the next step in

Here's a simplified version of an API function that handles post requests: myFunc(req: express.Request, res: express.Response, next){ let err = 'err detected!'; //validateSometing() returns a boolean value, true if validation pass f ...

floating containers aligned side by side in a perfectly positioned parent container

I'm currently working on aligning a set of buttons within a DIV popup that I've created. My goal is to have the buttons positioned next to each other, but I'm having trouble achieving this. I've attempted using 'float: left', ...

Enhancing TypeScript type definitions for the Response.render() method in Express

Struggling with enhancing the type safety of my Express project by extending the Response.render function. import { Response } from "express"; import { Product } from "../models/Product.interface"; export interface ProductListResponse ...

Transformation and swapping between two distinct visuals

In this scenario, there are two images: a boat and a plane. The specific effect desired is as follows: The boat should animate from left to right, while the plane remains hidden. Once the boat reaches the middle of the screen, it should disappear and the p ...

Nodejs and javascript are utilized to create dynamic SES emails

I have successfully implemented sending an email using node-ses client.sendEmail({ to: to_id, , cc: cc_id, , bcc: bcc_id, , subject: 'greetings' , message: 'your <b>message</b> goes here' , altText: 'plain text& ...

Determine the vertical dimension of a child division once it has been integrated into an HTML document

My goal is to create a website with multiple pages without having to recreate the toolbar for each page. To achieve this, I have created a separate HTML file and CSS file specifically for the toolbar. On each page, I simply import the toolbar using the fo ...

The response I am receiving is showing a 404 error even though the request was made correctly

Hello, I'm facing a strange issue while trying to set up a contact form using express and sendGrid. The functionality of sending messages is working fine, but I keep getting a 404 error on the request. It's puzzling how the messages are being del ...

Designating a class that applies to every Angular template that can be displayed using *ngIf

I have a specific CLASS called section that I want to apply to a DIV for rendering. Surprisingly, it functions as expected. <div *ngIf="decoded; then coordinates"></div> <ng-template #coordinates> <div class="section&q ...

Updating to Express 4 has caused issues with my sessions and passport functionality

After upgrading to express 4, I encountered an issue where the order of app.use had to be placed after my app.get and app.post routes. app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'public') ...

Updating your project from Express version 2.0 to 3.0

As a newcomer to node programming, I've been diving into tutorials that are mostly geared toward version 2.5.x. While I've checked out the migration page for Express, I'm struggling to find clear working examples tailored for beginners. My i ...