1

I am trying to wrap my html in a nodejs express app (latest version of express). I try using res.sendFile to send my "index.html" file. I am running into an issue where there are a lot of 404s when loading the page in a browser because it can't find any of my js or css files. My js files are in the bower_components directory, some are in "js" directory. My css files are in a "css" directory.

Path for one is:

/bower_components/jquery/dist/jquery.min.js

What is the best way to update in my server.js file and my index.html file so that it can find all the "css" and "js" files?

2 Answers 2

4

You can use the directive express.static

var server = express();
server.use(express.static(path.join(__dirname, 'static')));

It will look for a static folder to serve your static files. Just put your css and js files in this folder and reference them in the <head> part of your templates (index.html in your case)

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

Comments

2

If you have this two line of code in your app.js file:

app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));

Then you need to put your HTML files in view folder. I myself use ejs (templator) for render HTML files and more ,by adding this line of code to my app.js :

app.set('view engine', 'ejs');

Then by changing your extention of HTML fils to .ejs you can render them with this code :

res.render('file_name');

More info

For example if you have a css file in /public/css/style.css you have to link to it in your html with this address : ./css/style.css or something like this.

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.