Reputation: 3272
I use express on nodejs. The html-file I load doesn't get java-scripts and css-files.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>Hello, world!</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script type="" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.js"></script>
</body>
</html>
This is my express-part in nodejs:
app.get('/', function(req, res){
console.log(req.path);
fs.readFile('mongo_client/index.html',function (err, data){
if(!err)
{
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
}
else
{
res.writeHead(400, {'Content-Type': 'text/html'});
res.end("index.html not found");
}
});
});
The only console.log is "/" once. The css and js file isn't even requested.
Edit:
I used the static middleware but it doesn't work either:
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
fs.readFile('mongo_client/index.html',function (err, data){
if(!err)
{
res.send(data);;
}
else
{
res.send("index.html not found");
}
});
});
Therefore I put my js and css - data to the public - folder. Everytime I try to connect I download the index.html file. Does anyone have a working example for a simple webserver using express? Do I have to use the file-reader ... I think there's another way using express-middleware.
I just need a simple example of an express web-server that is supporting css and js ... I can't find anything that's just that basic.
Upvotes: 3
Views: 12078
Reputation: 7196
app.get('/') will only respond to requests at the root, not anything beyond that. Your css and other assets are at /css/bootstrap.min.css which your route doesn't handle.
But for express, use the static
middleware to do all that for you. http://expressjs.com/api.html#middleware
This article also explains the setup http://blog.modulus.io/nodejs-and-express-static-content
Update: a sample app
Express is capable of generating a sample app that supports static, with optional support for CSS pre-processors. Read their guide: http://expressjs.com/guide.html but the basic steps are to install express globally
npm install -g express
Then use the command line to generate the skeleton of your app
express --css stylus myapp
The above provides support for Stylus. You can specify less if you prefer. Or to generate it with support for basic css files
express myapp
Then cd into myapp, or whatever name you provided, and you can see how it's done.
Upvotes: 3