0

I'm trying to create a basic website on Node.js in order to learn. I have an html with some css and js files for the site. I want to serve this pages from Node.js, so I can make ajax calls to this later.

This is the code I have so far:

var express = require("express");
var app     = express();
var path    = require("path");


app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/views/index.html'));
});

app.listen(3000);

console.log("Running at Port 3000");

It loads the html correctly, but it does not find the resources css/js.

How should I implement a basic web server, where I can specify the page to return with the css/js resources I need?

Or maybe the question should be, is this the correct way to make the webpage using node?

1
  • check express-static module for serving static assests such as js css etc. also you will eventually want to use res.render instead of res.sendFile to be able to put some dynamic data into views Commented Nov 26, 2015 at 19:27

1 Answer 1

3

You are already using express, so best way is to define your public folder where you are putting your css or js files to make it available as static resource -

app.use(express.static(__dirname + '/public'));

public
 -css
  -style.css
 -js
  -script.js

then in your index.html file refer as -

<link rel="stylesheet" href="css/style.css" />
Sign up to request clarification or add additional context in comments.

3 Comments

So, I added this line before the app.get. with the folder my resources are. How should be the url to serve them now?
@Pablo yes add it before your routes
Yes, but how should now access that files?

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.