2

I am trying out node / express js and created a little web project.

I have the views in root /views directory

so:

root
  /views
  /css

I've added this to /views/index.html file:

<link rel="stylesheet" type="text/css" href="css/style.css" />

And this is my server.js file code:

var express = require("express");
var app = express();
var router = express.Router();
var path = __dirname + '/views/';
var path = __dirname + '/css/'; //Not working

router.use(function (req,res,next) {
  console.log("/" + req.method);
  next();
});

router.get("/",function(req,res){
  res.sendFile(path + "index.html");
});

router.get("/about",function(req,res){
  res.sendFile(path + "about.html");
});

router.get("/contact",function(req,res){
  res.sendFile(path + "contact.html");
});

app.use("/",router);

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

app.use("*",function(req,res){
  res.sendFile(path + "404.html");
});

app.listen(3000,function(){
  console.log("Live at Port 3000 - http://localhost:3000");
});

How can I get it to read my css files?

4
  • 2
    See expressjs.com/en/starter/static-files.html Commented Dec 13, 2015 at 9:44
  • I'm getting this error now after adding that code: Error: ENOENT: no such file or directory, stat '/var/www/html/css/index.html' at Error (native) Commented Dec 13, 2015 at 9:57
  • 1
    Try this: app.use('/css', express.static('css'));. I see that you just copy-pasted key line from the docs page I linked to - you have to make sure it's pointing at the right path specific to your project. Commented Dec 13, 2015 at 10:12
  • 1
    You want to create an answer ? It was you who solved the issue so I think it's fair that you get the answer Commented Dec 13, 2015 at 10:37

1 Answer 1

1

To serve static files using Express.JS, use its built-in express.static middleware.

Assuming following directory structure:

root/
  server.js
  css/
    styles.css

All you need is the following code in your server.js file:

var express = require('express');
var app = express();

// key line! - serve all static files from "css" directory under "/css" path
app.use('/css', express.static('css'));

app.listen(3000, function() {
  console.log('Live at Port 3000 - http://localhost:3000');
});

To make styles.css available under localhost:3000/css/styles.css address (and analogically for all other files kept in css directory).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.