How to add static css to node js app by express.static - javascript

I have a node.js app with a static css file. When I create a middleware and call the css file, it is geeting an error as follows:
Refused to apply style from 'http://localhost:3000/files/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Here is my app.js file
var express = require ('express');
var app = express();
app.set('view engine', 'ejs');
app.use('/files', express.static('/files'));
app.get('/', function(req, res){
res.render('index');
});
app.listen(3000);
index.ejs
<!DOCTYPE html>
<html>
<head>
<title>New page</title>
<link rel="stylesheet" type="text/css" href="files/style.css">
</head>
<body>
<p>New style</p>
</body>
</html>
When I use URL : http://localhost:3000/files/style.css
Display "Cannot GET /files/style.css" and when checking in the console's network tab, it says styles.css not found. This happens when I add static javascript files too.
I also tried this with follows
app.use('/files', express.static(__dirname + '/files'));
app.use(express.static(__dirname + '/files'));
app.use(express.static('files'));
and none of them has worked so far.
How can I solve this?

You try to get file from files/files/files/style.css
Try code below:
NodeJs:
app.use(express.static(path.join(__dirname, 'files')));
HTML:
<link rel="stylesheet" type="text/css" href="/style.css">

Related

ExpressJS error: MIME type ('text/html') is not a supported stylesheet MIME type

When launching my NodeJS server and typing localhost:8080, I get the previously mentioned error as it loads the page. Below is my head section in my index.html file, I'm not sure why this occurs, my index.html is in the same directory as script.js and style.css.
<head>
<meta charset="utf-8">
<title>Express & Node Test</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script src="script.js" type="text/javascript"></script>
</head>
Using the following snippet from my app.js file for ExpressJS routing.
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, "/web/index.html"));
});
I've had no success searching my problem so I have resorted to asking on StackOverflow, any help would be greatly appreciated.
You can set your code like this in order to serve files from the current directory, Instead of path.join you can use:
app.get('/', (req, res) => {
res.sendFile(__dirname + "/index.html"); });

Express.js cant apply stylesheet

When running my HTML+ExpressJS code i have ran into an issue to do with CSS. When i go to dev tools in the browser i see Refused to apply style from 'https://localhost:5000/public/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Code:
ExpressJS
const app = express();
app.use(express.static('public'));
app.get('/', (req,res) => {
res.sendFile('/home/pi/website/index.html');
});
app.listen(5000, () => console.log('http://localhost:5000'));
HTML:
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<title>homepage</title>
<link rel="stylesheet" type="text/css" href="public/style.css" media="screen" />
</head>
<body>
<h1 class=title>Hello!</h1>
<h1 class=title>This page is running NodeJS on a Raspberry Pi 4 4GB</h1>
</body>
</html>
Your link:
href="public/style.css"
will not work with
app.use(express.static('public'));
because that will be looking inside the public directory for public/style.css in your server file system which means it's actually looking for public/public/style.css and I assume you don't have the file system set up that way. You don't show exactly where style.css is in your server file system, but if it's directly in the public directory you are pointing express.static() at, then you should be using:
href="/style.css"

problems with ejs includes and partials

I'm trying to make a dynamic include using ejs, but my css is working only on the main page (mainPage.ejs), but not on the login page (loginPage.ejs). My folders are organized as follows:
app.js below
require('dotenv').config();
const express = require('express');
const app = express();
const path = require('path');
const mongoose = require('mongoose');
const helmet = require('helmet');
const routes = require('./src/routes/routes');
mongoose.connect(process.env.DATABASE_KEY, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
console.log('Connected to the database');
app.emit('ready');
})
.catch((err) => console.log(err));
//app.use(helmet());
app.use(express.urlencoded({ extended: true}));
app.use(express.json());
app.set('views', './src/views');
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use(routes);
app.on('ready', () => {
app.listen(3000);
})
Here is my head.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />
<link rel="stylesheet" href="css/style.css"/>
<title>Home</title>
</head>
<body>
loginPage.ejs
<%- include('./includes/head')%>
<div class="test">
donĀ“t work
</div>
<%- include('includes/footer')%>
As I said, css is only working on mainPage.ejs, and there the includes were imported as follows:
<%- include('./includes/head')%>
...html
<%- include('includes/footer')%>
In loginPage.ejs the css for some reason is not working even though the includes are exactly the same as the mainPage. I tried to see if the problem was in some configuration made in app.js, but I still couldn't solve it.
I had a similar problem recently. If someone is still struggling with this.
This is how I solved it:
Put views and css in one folder. In your case, you can put the src folder inside the public folder.
Then in app.js change -> app.set('views', './src/views'); -> app.set('views', './public/src/views');
Adjust your css and other paths in your app respectively.

Js file not loading in node js server

I have a node js server when I run HTML page in local host i get the error Uncaught SyntaxError: Unexpected token < in the console because my local js and css files are not able to be loaded.
i have gone through - Node.js serve HTML, but can't load script files in served page
but it didn't worked
i have a file structure
enter image description here
my server code server.js
Node js:-
var express = require('express');
var http = require('http');
var fs = require('fs');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('*', function(req, res) {
console.log("Global");
res.sendFile(__dirname + '/public/index.html');
});
var port = process.env.PORT || 7000;
http.createServer(app).listen(7000);
My HTML file index.html is
<!DOCTYPE html>
<html>
<head>
<title>sample spa app</title>
<link rel="stylesheet" type="text/html" href="css/style.css">
</head>
<body>
<li>home</li>
<li>about</li>
<div>
<h2>you are in index.html</h2>
</div>
<div id="app">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
<script src="public/js/app.js" type="text/javascript"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>sample spa app</title>
<link rel="stylesheet" type="text/html" href="css/style.css">
</head>
<body>
<li>home</li>
<li>about</li>
<div>
<h2>you are in index.html</h2>
</div>
<div id="app">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="./js/app.js" type="text/javascript">
</script>
</body>
</html>
<link rel="stylesheet" type="text/html" href="css/style.css">
The static handler will try and find a file sampleProject/public/css/style.css
<script src="public/js/app.js" type="text/javascript"></script>
The static handler will try and find a file sampleProject/public/public/js/app.js (yes, I wrote public/public).
None of these exist, therefore the static handler lets the request pass to the next route. The next route forces sampleProject/public/index.html to be served, whatever the request is. Hence your error.
Option A: isolate statically-served files
app.use('/public', express.static(__dirname + '/public'));
(As a side note you should require('path') and declare express.static(path.join(__dirname, 'public')), which is safer and more portable than manually concatenating.)
This tells the application to use the static handler only if the route begins with /public.
Option B: always try to resolve files as static
Move your css folder to public/css, and change the path when calling your JS to:
<script src="/js/app.js" type="text/javascript"></script>
Read about the bases here.

Refused to apply style from 'http://localhost:3000/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type

I am just creating an example website template, and am getting this error in the Chrome console:
Refused to apply style from 'http://localhost:3000/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
I am getting a 404 error when trying to load the css/style.css page, but the path seems correct. Below is some of the basic code for the site:
App:
var express = require('express');
var app = express();
var exphbs = require('express-handlebars');
var path = require('path');
app.engine('hbs', exphbs({extname:'hbs'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, "static")));
app.get('/', function(req, res) {
res.render('resume.hbs')
})
app.listen(3000)
HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<base href="/">
<link rel="stylesheet" href="..\css\style.css" type = "text/css">
<title>Example Website</title>
<h1>Header</h1>
<hr id = 'headerBorder'>
</head>
<body>
</body>
</html>
CSS:
h1 {
color: blue
}
Below are what the folders look like, which shows the path. I cannot seem to find a way to fix this. Any ideas?
This is likely just caused by not having the expected path.
You're using this line here:
app.use(express.static(path.join(__dirname, "static")));
So in this case, you need a folder named "static" and inside that folder you can put your css and images. You would be able to link to them as follows:
<link rel="stylesheet" href="/css/style.css" type="text/css">
Reference: https://expressjs.com/en/starter/static-files.html
Since you are working with hbs, create "public" folder and keep your static folders, css,javaScript,img inside the "public" folder. then
const path = require("path");
app.use(express.static(path.join(__dirname, "public")));
Here is the magic, since you told express that use "public" as a static folder, when you link the files inside that folder, hbs will take "public" folder as the "root" folder.
So lets say you have main.css in folder "style" inside the folder ""public", "public/style/main.css" directory, when you link main.css:
<link rel="stylesheet" href="style/main.css" type="text/css" />
Also, this is the complete setup for hbs in express:
app.set("view engine", "hbs");
app.engine(
"hbs",
expressHbs({
defaultLayout: "layout",
extname: ".hbs",
layoutsDir: __dirname + "/views/layouts",
partialsDir: __dirname + "/views/partials"
})
);
Place all your css inside a folder - call it static or public.
So your css is located at public/css/style.css.
In your app.js, you would reference static files by:
app.use(express.static(path.join(__dirname, "public")));
The path of the public folder should be relative to the app.js file.
just make a folder called static. and put your css folder and image folder in static folder.
Don't forget to first make css folder to keep all css files and image folder for all images.
your code:
app.use(express.static(path.join(__dirname, "static")));
in this code you are saying express to look at static folder and because you don't have static folder you are getting error and your css and image are not applying on your website.
Sol:
First create a folder static and transfer css folder to static folder.
2.In html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<base href="/">
<link rel="stylesheet" href="css\style.css" type = "text/css">
<title>Example Website</title>
<h1>Header</h1>
<hr id = 'headerBorder'>
</head>
<body>
</body>
</html>
Js file
var express = require('express');
var app = express();
var exphbs = require('express-handlebars');
var path = require('path');
app.engine('hbs', exphbs({extname:'hbs'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(express.static("static"));
app.get('/', function(req, res) {
res.render('resume.hbs')
})
app.listen(3000)
I tried to change the different slashes as well, but that does not entirely solve the problem. Propably, the bootstrap CSS defines h1 already as well. You therefore need to change the order of the CSS files in your HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/style.css" type="text/css">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<base href="/">
<title>Example Website</title>
<h1>Header</h1>
<hr id = 'headerBorder'>
</head>
<body>
</body>
</html>
Adding only !important to your CSS does not solve the issue.

Categories

Resources