Reputation: 1524
I have the following code on my node.js server (I'm using express):
app.get('/appointment/:id',function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.write('<link href="public/css/style.css" rel="stylesheet" type="text/css">');
res.write('<form name="accept" action="http://localhost:8080/appointment/'+ req.params.id+'/1" method="post">');
res.write('<input id="accept" type="submit" value="Accept">');
res.write('</form><br>');
res.write('<form name="decline" action="http://localhost:8080/appointment/'+ req.params.id+'/0" method="post">');
res.write('<input id="decline" type="submit" value="Decline">');
res.write('</form><br>');
res.end();
});
In my root folder I have folder appointment/public/css/style.css.
When I open the web page it just displays 2 form buttons but without CSS applied.
The CSS code is:
#accept {
width:50px;
height:30px;
background-color:#00FF00;
color:#FFFFFF;
font-weight:bold;
font-size:120%;
}
#decline {
width:50px;
height:30px;
background-color:#FF0000;
color:#FFFFFF;
font-weight:bold;
font-size:120%;
}
What is the problem and how can I fix it?
EDIT: The hierarchy is as follows:
-server_files
--nodeServer.js
--public
---css
----style.css
Upvotes: 0
Views: 2711
Reputation: 2258
I feel it's important to share with you the reason of why this problem occurred. Just like other web frameworks, ExpressJs has it's own way of serving static files.
express.static middleware is based on serve-static, and is responsible for serving the static assets of an Express application.
How it works:
Serve static content for the app from the "public" directory in the application directory
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static"
// GET /static/style.css etc.
app.use('/static', express.static(__dirname + '/public'));
Serve static files from multiple directories, but give precedence to "./public" over the others
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/files'));
app.use(express.static(__dirname + '/uploads'));
I checked your folder structure, i suggest you to keep your public directory in the same level as server_files directory and also nodeServer.js file outside of your server_files because it's the main file using which you are using to start your application.
Then in your nodeServer.js you can do this:
app.use('/public', express.static(__dirname + '/public'));
After doing this, all your static assets in public directory can be accessed in html templates or any other templating engine that you might be using. For example :
<link href="public/css/style.css" rel="stylesheet" type="text/css">
Please note the order of your middle wares in nodeServer.js. I hope this helps.
Upvotes: 2