0

I'm making a simple client/server connection via node.js modules and a simple HTML page.

the html page is this:

<script type="text/javascript" src="index.js"></script>

Where the index.js file in the same directory is this:

alert("hello!");

This works fine when I manually click on the html page, but when I invoke it using my app.js:

var express = require("express");
var app = express();
var server = require('http').Server(app);

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/web/index.html');
});
app.use('/web', express.static(__dirname + '/web'));
server.listen(2000); 

console.log('Started Server!');

by calling

node app.js

it does not show the alert when the HTML page loads. I just installed node.js and installed the node express dependencies in this app after I called "node init" on the project.

6
  • Also, for more clarification, I can do <script> alert("hello!"); </script> in the index.html and the alert will show up on the node server. I just don't know why I can't do the same if I call the script source Commented Jun 10, 2017 at 20:47
  • Is the script loading from the server in the network tab? Commented Jun 10, 2017 at 20:49
  • The script is in the same directory as the index.html file. I don't know what you mean by "script loading from the server"? Commented Jun 10, 2017 at 20:52
  • Look at the network tab on your client and see the path that is being requested for the index.js file. You're likely getting a 404 for the requested resource. I bet it's requesting localhost:2000/index.js which corresponds to nothing on your server. Commented Jun 10, 2017 at 20:59
  • You're right, its 404, but why would this be the case? I have it in my app.js to load items from the /web directory? Commented Jun 10, 2017 at 21:07

1 Answer 1

2

The path for index.js and static folder does not match. Therfore it fails to load index.js.

This should work:

app.use('/', express.static(__dirname + '/web'));
server.listen(2000);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I should probably read up on how express works too!
You're welcome. You can also use app.use(express.static(__dirname + '/web'));, without any route, if it is supposed to work for all routes.

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.