Reputation: 1362
I have a simple doubt but can't figure it out. I am starting node js app,from a localhost location and through the response i am sending a html file. But its node loading the script file which is inside the html.
Node js file
var express = require('express');
var app = express();
var ExpressPeerServer = require('peer').ExpressPeerServer;
app.get('/', function(req, res, next) {
console.log("before redirection");
res.sendfile('index.html'); });
var server = app.listen(9000);
var options = {
debug: true
}
app.use('/api', ExpressPeerServer(server, options));
server.on('connection', function(id) {
console.log("In Server connection")
});
server.on('disconnect', function(id) {
console.log("server Disconnected")
});
Html File
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://cdn.peerjs.com/0.3/peer.js"></script>
<script type = "text/javascript" src="script.js"></script>
</head>
<body>
<h1>ha ha this is Webrtc</h1>
</body>
</html>
script.js
function webRtcInit() {
alert("Inside Script")
}
$(document).on('ready', webRtcInit());
When i normally run the html file its loading the script file. But when i send the file through node js and load the script, I am getting the error , that it cannot get the script file, Why is this happening...?
Thanks
Upvotes: 0
Views: 5109
Reputation: 25064
I am seeing few problems in your code:
this renders your html page, similarly, you need one for script.js
.
app.get('/', function(req, res, next) {
console.log("before redirection");
res.sendfile('index.html');
});
either specific:
app.get('/script.js', function(req, res, next) {
console.log("before redirection");
res.sendfile('index.html');
});
or generic:
app.use(express.static('static')); // now place your static files in the static folder.
unrelated to the problem at hand, but, in script.js
, it is webRtcInit
not webRtcInit()
:
$(document).on('ready', webRtcInit);
Upvotes: 4
Reputation: 708206
A node.js server does not serve any files by default (this is different that some other web servers). So, any file that you want it to serve must have a route for it or some type of middleware that handles it.
So, your code does have a route for /
, but when the browser parses the index.html file that you return from that route and then tries to load script.js
from your node.js server, you don't have a route for that and the server will return a 404 (not found).
The solution is to create a route for script.js
. Since it's a static resource, you can probably use the express.static capability to serve all your static files. You can read about serving static files in express here.
Upvotes: 4