Rando Hinn
Rando Hinn

Reputation: 1322

NodeJS Express sendFile that includes external JS files

So, I have a file structure like this:

App
 client
   index.html
   App.js
 server
   node_modules
   package.json
   server.js

the server.js is the server file ran by node, it serves up the index.html

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



app.get('/', function(req, res){
   res.sendFile("client/index.html",{ root: '../' });
});




http.listen(3000, function(){
  console.log('Server is listening on port 3000');
});

So the index.html includes the App.js in it's head, like you normally would

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

The problem is, that App.js is never found and included when I connect. Gives a 404. How could I fix it?

Upvotes: 1

Views: 2755

Answers (3)

Kent Aguilar
Kent Aguilar

Reputation: 5338

This one solved mine. You can check this out.

var express = require('express');
var app = express();
app.use('/js', express.static(__dirname + '/public/js'));

Thus, my app.js can be accessed via -> http://localhost:3000/js/app.js

Upvotes: 1

V31
V31

Reputation: 7666

looking at your server folder structure you need to access using the path ./client/App.js, instead of only App.js

So your script tag will look like,

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

Upvotes: 0

Herku
Herku

Reputation: 7666

Your server doesn't seem to do anything but sending client/index.html when http://127.0.0.1:3000 is requested in a browser. So what actually happens, when the browser received the index.html, it sends another request to http://127.0.0.1:3000/App.js. But your Server can't answere that request. It can only anwere requests for the index. If you want a static server check out serve-static on Github: https://github.com/expressjs/serve-static Or you could write another route for you app anwering with the App.js as you did for the index.html.

Upvotes: 1

Related Questions