how can i include JavaScript file in node.js app? - javascript

i am accessing the script.js and libs.js in index.html like this:
<body style='margin:0px' >
<canvas id='your_canvas'
style='position: absolute; background-color: black;'></canvas>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="/libs.js"></script>
<script type="text/javascript" src="/script.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
main(); //this function is inside of script.js
});
</script>
but the .js files cannot be accessed and showing error:
1) GET script.js 404 (Not Found) localhost/:12.
2) GET libs.js 404 (Not Found) localhost/:11.
3) Uncaught ReferenceError: main is not defined (index):17.
where am i going wrong and how can i include these two JavaScript files using node.js?
my app.js is :
var express = require("express"),
app = express(),
server = require("http").createServer(app),
io = require("socket.io").listen(server);
server.listen(8000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
app.use(express.static(__dirname + '/public/script.js'));
app.use(express.static(__dirname + '/public/libs.js'));
io.sockets.on('connection', function(socket) {
socket.on('send coordinates',function(data){
io.sockets.emit('coordinates', data);
});
});
and then i have my script.js and libs.js files.

You need to actually serve these files if you want them to be accessible. You can't just include them in your project directory. If you are using Express, you can designate a static file directory like this:
app.use(express.static(__dirname + '/public'));
You can also use node-static or even create a handler for each file...
Using express, your code should look something like this (Not tested):
var express = require("express");
var app = express();
app.server = require('http').createServer(app);
var io = require("socket.io").listen(app.server);
app.get('/', function(req, res){
res.sendfile(__dirname + '/public/index.html'); // I would move this file to public
});
app.use(express.static(__dirname + '/public'));
io.sockets.on('connection', function(socket) {
socket.on('send coordinates',function(data){
io.sockets.emit('coordinates', data);
});
});
app.server.listen(8000);

Are you trying to call:
<script>
jQuery(function($){
main(); //this function is inside of script.js
});
</script>
If you are then you need to save your code as a file named script.js in the root directory. Adding javascript/jQuery between tags in your html does not need to be called and will run automatically.
I'd advise laying your script out in the following way too, i don't recognize the way you have laid it out.
<script>
var main = function() {
\\Your javascript/jQuery
}
$(document).ready(main);
</script>

Related

HTML file can't find embedded js files

I'm currently trying to make a game using Node.js, Express, and Socket.io. However, when I attempt to run it locally I get a 404 error stating that my javascript files can't be found. My file structure looks like this:
root
| game
| | game.html
| | game.js
| index.js
And my code looks like this:
index.js
//Dependencies
var express = require('express'); //Pulls in Express framework
var http = require('http') //Pulls in http module
var socketio = require('socket.io'); //Pulls in Socket.io framework
//Instance Declarations
var app = express(); //Creates an Express instance
var server = http.createServer(app); //Creates an http server using the Express framework
var port_to_listen = process.env.PORT || 3000; //Specifies which port to listen on
var socket = socketio(http); //Creates Socket.io instance related to the server just created
//Default page displayed, always sent to index.html
app.get('/', (req, res) => {
res.sendFile(__dirname + '/game/game.html');
});
//Tells the server to listen for any incoming inconnections
server.listen(port_to_listen, () => {
console.log(`listening on ${port_to_listen}`);
});
socket.on('connection', function(client) {
console.log('Connection made')
});
//Testing to ensure socketio works
setInterval(function() {
socket.sockets.emit('message', 'hi!');
}, 1000);
game.js
var socket = io();
socket.on('message', function(data) {
console.log(data);
});
game.html
<html>
<head>
<title>A Multiplayer Game</title>
<style>
canvas {
width: 800px;
height: 600px;
border: 5px solid black;
}
</style>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script type = "text/javascript" src="game.js"></script>
</html>
The error messages look like this:
What should I do to fix these errors?
Edit:
These errors also still persist when I change the src path for game.js to
<script type = "text/javascript" src="/game/game.js"></script>
You have only one route that serves files:
app.get('/', (req, res) => {
res.sendFile(__dirname + '/game/game.html');
});
The rest of the files (your css, js, etc.) are not served automatically
You need to create route(s) for that, like explained here Serving static files in Express

Why does index.html load the css or js modules, does a request as if they were directories?

I'm writing a simple server with expressjs:
'use strict';
var express = require('express');
var logger = require('morgan');
var path = require('path');
var bodyParser = require('body-parser');
var api = require('./routes/main');
var app = express();
app.disable('x-powered-by');
app.use(logger('dev')); //Used to log HTTP requests
app.use(bodyParser.urlencoded({ extended: true })); //Used to automatically parse requests body
app.use(bodyParser.json());
app.use('/api', api);
app.use('/*', express.static('./public')); //serving static files under public folder
app.use(function(req,res){
res.send("404");
});
var server = app.listen(8000, "0.0.0.0", function () {
console.log('RAVE listening on port ' + server.address().port + 'hosting at ' + server.address().address);
});
module.exports = app;
in public directory there are index.htm, some css files and one js script, When index.html tries to load css or js scripts, it does through GET /path/file.css/ and loads a directory instead of file.css. Why??
index.html:
<head>
....
<link rel="stylesheet" href="/stylesheets/view-style.css" type="text/css" />
<script type="text/javascript" src="/js/main.js"></script>
</head>
console:
GET /stylesheets/view-style.css/ 200 8.979 ms - 10602
GET /js/main.js/ 200 8.598 ms - 10602
chrome sources:
I know you have already solved the problem . But just for future reference .
We have something called cache-busting . Basically use
<script type="text/javascript" src="/js/main.js?version=1"></script>
Whenever you change the file change the version number in the code above

CSS doesn't load into my HTML code using Node.js

I'm trying to add CSS to my HTML using express() function in localhost:3000 by Node.js.
Unfortunately, something is weird. I followed the steps from tutorial step by step but still my css doesn't load. My style.css is in css folder (css/style.css). Here is my code:
app.js (note that I used app and app1)
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var express = require('express');
var app1 = express();
var mySocket = 0;
app1.use(express.static('/css'));
app.listen(3000); //Which port are we going to listen to?
function handler (req, res) {
fs.readFile(__dirname + '/index.html', //Load and display outputs to the index.html file
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log('Webpage connected'); //Confirmation that the socket has connection to the webpage
mySocket = socket;
});
//UDP server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("Broadcasting Message: " + msg); //Display the message coming from the terminal to the command line for debugging
if (mySocket != 0) {
mySocket.emit('field', "" + msg);
mySocket.broadcast.emit('field', "" + msg); //Display the message from the terminal to the webpage
}
});
server.on("listening", function () {
var address = server.address(); //IPAddress of the server
console.log("UDP server listening to " + address.address + ":" + address.port);
});
server.bind(41181);
style.css (css/style.css)
.test
{
color:red;
}
index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<link rel="stylesheet" type="text/css" href="/css/style.css" />
</head>
<body>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('field', function (data) {
console.log(data);
$("#field").html(data);
});
</script>
<div class='test'>Data from C#: </div><div id="field"></div>
</body>
</html>
You set the root of the static module to /css here
app1.use(express.static('/css'));
but then you request /css/style.css which means express looks for the file in /css/css/style.css (note that this path is absolute and not relative to your project).
Put everything in a public folder, e.g. public/css/style.css and then
app1.use(express.static(__dirname + '/public'));
Edit: Here's a minimal working example which serves the index.html and the style.css (in public/css/style.css)
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/index.html', function(req, res, next) {
res.sendFile(__dirname + '/index.html');
});
app.listen(3000);

Socket.emit not going through

index.js
var app = require('express')();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
server.listen(process.env.PORT || 3000);
app.use(require('express').static(path.join(__dirname)));
console.log('server running');
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
var addedUser = false;
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', data);
});
});
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
When I start up the server, the console logs "server running" fine. I can't get the submit post button to do anything. None of the debug console messages appear and nothing happens. It's supposed to emit "new post" when the submit button is clicked but it looks as if nothing goes through
I was able to get your code to work on my own computer like this:
index.js
var express = require('express');
var app = express();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'index.html'));
});
app.use(express.static(__dirname));
console.log('server running');
io.on('connection', function (socket) {
console.log("connection");
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', post);
});
});
server.listen(process.env.PORT || 3000);
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="/client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
Changes to index.js
Define express variable so it can be reused.
Define app.get() before app.use(express.static(...)) so we're sure to serve index.html with the app.get() and not from the static location.
Change res.sendfile() to res.sendFile()`
Change socket.emit("posted", data) to socket.emit("posted", post).
Move server.listen() to end after everything else is set up.
Remove path.join() from express.static() call since it is not needed there.
Add path.join() to res.sendFile() call for cross platform safety in path building.
Of these, the only one I'm sure was causing an error was #4, the others are good housekeeping.
Changes to client.js
None
Changes to index.html
Change path to client.js to /client.js.
If this code doesn't work on heroku, then you either don't have files positioned in the right directories or heroku is not configured properly to allow your app or socket.io to work properly. If I were you, I would first verify that this code work on your own local computer and only then, go try it on heroku to eliminate variables first.

NodeJS res.sendFile not sending images or directorys

so as said above, i run the html file only and i'm able to see the pictures, but when i run the file via node it sends me a 404 error on the file i used.
<html>
<body>
<img src="aaa.jpg" />
<script src="/socket.io/socket.io.js">
</script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
</script>
</body>
</html>
and the node code
var app = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http);
app.get("/", function (req, res) {
res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
console.log("Server Open");
});
how can i stop this from happening?
To serve static files such as images and scripts, you need to include a middleware that serves static files. Put all your static files inside of a public directory and serve them like this.
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
// Serve static files
app.use(express.static(__dirname + '/public'));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
console.log("Server Open");
});

Categories