1

I want to load client side javascript chat.jsand css style.css in my html file but i get a 404 error while loading them.

This is my server file:

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

This is my client html:

<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="chat.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">

How can I load them in my app? All files are in the same root folder. I tried this but it doesn't work:

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/chat.js');
});
1
  • 1
    You should read an express beginners tutorial / getting started guide Commented Jul 7, 2015 at 20:33

1 Answer 1

5

Looks like you are using express web framework so in that case you should use the express static middleware for your purposes.

I did an example that is below.

here is the server server.js file:

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

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

app.listen(4040, function() {
  console.log('server up and running');
});

Where you see that Express is serving the files that resides on public directory. You see I didn't provide a route for / since the browser automatically is going to grab the index.html.


public/index.html:

<!doctype html>
<html>
  <head>
    <link href="style.css" rel="stylesheet"/>
  </head>
  <body>
    <h1>Hey</h1>
    <script src="app.js"></script>
  </body>
</html>

From the perspective of the browser he only knows the index.html, app.js, and style.css files since they were provided by express.


public/style.css:

body {                                                          
    background: red;                                            
}

public/app.js

document.addEventListener('DOMContentLoaded', function() {
  alert('hello world');
});
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.