ltedone
ltedone

Reputation: 639

Provide an HTML page with JS with node.js and express

I am trying to serve an html page with a linked js script using node.js and express. This is the server that provide the page:

var express = require("express");
var app2 = express();
app2.get('/', function(req, res) {
   res.sendfile('./index.html');
});
app2.listen(process.env.VCAP_APP_PORT || 3000);

and this is the page:

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
</head>
<body>
    <h1>Demo</h1>
    <script src="/js/socket.io.js"></script>
    <script src="/js/codice.js"></script>
</body>

As you can see I have two js scripts in my js folder but they are not loaded when I launch the page. What can I do?

Upvotes: 0

Views: 352

Answers (1)

James Allardice
James Allardice

Reputation: 166061

What you would normally do is place any public resources (JavaScript files, CSS files, images etc) in a directory (Express names it public by default) and then use the express.static middleware in your app.configure call:

app.configure(function () {
    // Various other middleware functions...
    app.use(express.static(path.join(__dirname, "public")));
});

This effectively runs a static file server which will return any file inside the public directory. Currently, your browser is making a request for your JS files, but the Express server doesn't know what to do with them. They will eventually time out.

If you generate the initial state of your app with the global express executable (available if you installed Express via npm globally), it will set most of this up for you.

Upvotes: 2

Related Questions