Reputation: 339
I am trying to place static files in my public folder such as the html,css and js files but they won't fetch to the get url ('/'). Here is my folder structure
app.js
node_modules
--express
package.json
public
--style.css
My app is:
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
app.use('/assets', express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.send('<html><head><link href=assets/style.css type=text/css rel=stylesheet/></head><body><h1>Hello World</h1></body></html>');
});
app.get('/person/:id', function(req, res){
res.send('<html><head></head><body><h1>Person: ' + req.params.id + '</h1></body></html>');
});
app.get('/api', function(req, res){
res.json({ firstname: 'John', lastname: 'Doe' });
});
app.listen(port);
Style code is:
style.css:
body {
font-family: Arial, Helvetica, sans-sarif;
}
Upvotes: 0
Views: 334
Reputation: 40842
Your problem is, because
<link href=assets/style.css type=text/css rel=stylesheet/>
is equal to
<link href=assets/style.css type=text/css rel="stylesheet/">
If you don't use quotes then the value is terminated by one of the following characters: "
, '
, =
, >
, <
, or `
(See W3C: 4.4. Attributes for more details). As of that your value is terminated by the >
value is stylesheet/
.
Because of that the rel
of your link
is stylesheet/
instead of stylesheet
and thats why no stylesheet is loaded.
So either you have to add a space between stylesheet
and /
:
<link href=assets/style.css type=text/css rel=stylesheet />
or you need to use quotes.
Upvotes: 2
Reputation: 2474
There is syntax error in your HTML statement that links to the CSS file. You forgot to enclose the values in double quotes.
Please use the following format:
<link rel="stylesheet" type="text/css" href="assets/style.css">
If you are using ES6 supporting Node.JS then you can use the back-ticks(``) to better format the inline HTML code like:
app.get('/', function(req, res){
res.send(`
<html>
<head>
<link rel="stylesheet" type="text/css" href="assets/style.css">
</head>
<body>
<h1>Hello World</h1>
</body>
</html>`
);
});
Upvotes: 0
Reputation: 4309
Can you rename "public" to "assets", then use...
app.use(express.static('assets'));
Upvotes: 0