skip to Main Content

I was trying to test the Start Bootstrap Bare template using Node.js and Express. (Link to Start Bootstrap Template)

I did not modify anything within the HTML, CSS and JavaScript provided with the template. I only made a new index.js used to run Node.js. Here is the index.js code inside the project folder:

// using ES6 Modules syntax
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
const port = 4000;

// 👇️ for serving static files
app.use(express.static(__dirname + '/public/'));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});

When trying to run the page in localhost and the port it only displays the HTML, without the CSS and Bootstrap. I inspected the page and opened the console, displaying the following error messages:

Refused to apply style from 'http://localhost:4000/css/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
(localhost/:1)
        
GET http://localhost:4000/js/scripts.js net::ERR_ABORTED 404 (Not Found) (localhost/:48)

Refused to execute script from 'http://localhost:4000/js/scripts.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
(localhost/:1)

Is there any way to make this work? It should run the same way I run the HTML, CSS and JavaScript from the template (without the Node.js).

2

Answers


  1. Better way for call your css and js like below image code

    enter image description here

    Login or Signup to reply.
  2. Change from this

     // 👇️ for serving static files
        app.use(express.static(__dirname + '/public/'));
    

    to this

    // 👇️ for serving static files
    app.use(express.static(__dirname + '/public'));
    

    Notice that /public does not have a forward slash at the end.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search