nickcorin nickcorin - 2 months ago 9
HTML Question

Cannot include JS files in ExpressJS served index file

I'm building a web application at the moment, which has multiple pages incorporated. Each of these pages, however, have multiple views. The original design was to set each of the pages up as an SPA and just serve the

index.html
from the Node.js back-end and let React.js handle all the view routing.

This has proven to be more complex than I thought. Here is the issue.

The Node.js route (snippet):

router.get("/", function(request, response){
response.sendFile("/index.html", {
root: __dirname + "/../client/pages/home/"
});
});


But then in
index.html
(snippet):

<html>
<head>
<title>New Website</title>
</head>
<body>

<h1>Welcome to my website..</h1>

<div id="App">
</div>

<script src="index.js"></script>
</body>
</html>


The
index.js
is not being included. When the browser tries to include
index.js
it's requesting the route
www.example.com/index.js
from the Node.js server which is obviously not set up so I'm getting a
Cannot GET /index.js
response.

Each of the SPAs are in their individual folders with
index.html
and
index.js
. Creating a public folder with all the js files is not an option at the moment.

==========================================================================

SOLVED: THIS IS THE CODE I USED



clientController.js


module.exports = function(app){
router.get("/", function(request, response){
app.use("/", express.static(__dirname + "/../client/pages/page1/"));
response.sendFile("index.html", {
root: __dirname + "/../client/pages/page1/"
});
});

router.get("/page2/*", function(request, response){
app.use("/", express.static(__dirname + "/../client/pages/page2/"));
response.sendFile("index.html", {
root: __dirname + "/../client/pages/page2/"
});
});

return router;
};


server.js


var routes = require("controllers/clientController.js");
app.use("/", routes);


The accepted answer, I had to add in the
sendFile()
line as well to prevent the request from hanging. This settles the response and allows for the correct paths for file includes in the HTML files.

Answer

Your directory will be treated as static. You don't need to make a separate directory or define a separate route.

router.use(express.static( __dirname + "/../client/pages/home/"));
Comments