Aissa El Ouafi Aissa El Ouafi - 4 months ago 10
Node.js Question

Include .css and .js file in Node.js project

I used Node.js and Angular.js to build a simple web application based on Express framework, when I try to upload a

.css
file, I got the following error message :

“The stylesheet was not loaded because its MIME type, ”text/html“ is not ”text/css"


server.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var pg = require('pg');
var jwt = require('jsonwebtoken'); // create, sign and verify tokens
var morgan = require('morgan');
// Application front end
app.get('*',function(req,res){
res.sendfile('./public/index.html')
})
app.listen(port);
console.log('LogAnalysisWebApp happens on port '+port);


index.html

<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Log Analysis Web APP</title>
<link rel="stylesheet" type="text/css" href="/public/stylesheets/style.css">
</head>
<body>
<h1>Text Example</h1>
</body>
</html>


My project has the following structure :

Project structure

Answer

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

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

Now, you can load the files that are in the public directory:

http://www.domain.com/stylesheets/style.css

Here is the official documentation page on serving static resources.

Comments