How to include JS file in HTML, using NodeJS Express server? - javascript

I'm creating a chat, using server Express of NodeJS and AngularJS for manager in client side
But when I try include /js/code.js in my html, it can not found, because is not routed by Express
<!-- my include in html -->
<script src="./js/code.js"></script> <!- this is not found in execution -->
Meu index.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require("socket.io")(http);
app.get('/', function(request, response){
response.sendFile(__dirname + '/index.html');
});
How to can I fix this problem, without route all js file I will using in my project or routing all js file in path a lot?

Use app.use to specify your public files to your node app, like below
app.use(express.static(yourPublicPath));
EDIT:
You are getting "Express undefined" error because it is not defined. You can easily fix this by defining your app in 2 stages:-
var express = require('express');
var app = express();
On a side note, I would strongly recommend to go through Expressjs docs to learn more about Express.

Related

Issues with using Socket.io

I am trying to use socket.io for the first time, Im using it with a MEAN Stack. I have set it up the following way.
Server.js
var express = require('express');
var app = express(); // create our app w/ express
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.listen(port);
io.on('connection', function(socket) {
socket.emit('message', {
'message': 'hello world'
});
});
HTML File
<script>
var socket = io.connect();
socket.on('message', function(data) {
console.log(data.message);
});
</script>
I couldn't find the socket.io.js file so I searched for a CDN for the script. I used the following.
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.js"></script>
I tried downloading the socket.io.js from their website but the website seems to be down. I can access it, I get the 502 BAD GATEWAY error (http://socket.io)
When I load my HTML page after setting everything up as shown above I get the following error in the console.
Any help will be greatly appreciated!
UPDATE:
The socket.io server will perform some magic to provide that file when you retrieve it like this:
<script src="/socket.io/socket.io.js"></script>
EDIT: ah, I see the problem: your Express setup is incorrect.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.listen(port);
You're attaching socket.io to a server created by http.createServer, but with app.listen() you're actually creating a new server, one that socket.io isn't attached to.
You can make the setup a bit simpler:
var express = require('express');
var app = express();
var server = app.listen(port);
var io = require('socket.io')(server);
No need to use http.
As of now, socket.io website is still down. If you don't have the file in your server, it does not help using /socket.io/ because this points to a route on your server and that route doesn't seem to exist on your app. With this config, you need to be serving the .js file statically from your server - but I don't see that on your server code.
When you try the CDN, make sure the file is being loaded.

How to combine socket.io with some of the simple static http servers on Node.js?

I have created a Socket.IO application and I even already got some interactivity working. But I still host static content on Apache HTTP server (localhost, XAMPP bundle). Actually when running Node.js, this is my working directory:
C:\xampp\htdocs\game>node nodeGame.js
I'd like to move it all somewhere else, probably convert it into npm package and use Node.js to serve HTML and JavaScript files to user. It would be best if I could just install some simple handler that could be passed into http. Something like:
var http = Http.Server(require("really-simple-http-server"));
var io = SocketIo(http);
// Sockets below
None of the servers I found on StackOverflow seemed that simple, so which is most suitable for this purpose and how to use it?
You can use socket.io with the Express framework (using Express as your web server) and then use express.static() to serve static files:
var express = require('express');
var app = express();
var server = app.listen(3000, function() {
console.log("server started on port 3000");
});
var io = require('socket.io').listen(server);
// set up static file serving from the public directory
app.use('/static', express.static(__dirname + '/public'));
Details on the options for serving static files with Express are here.

Express and node.js run from a folder; all links point to url root

I have installed node inside a folder and am forwarding it through apache. I am doing this because I have several virtualhosts run through apache, and I do not want to take the time to set up everything through node.
Apache and Node.js on the Same Server
However, I am trying to create a chat engine. I try to include some js files, but they search for http://example.org/myscript.js instead of http://example.org/chat/myscript.js
I got around this by using
<base href="/chat/">
However, now I am trying to integrate socket.io. I included socket.io from https://cdn.socket.io/socket.io-1.3.5.js because I could not get the locally serverd /socket.io/socket.io.js to properly be located.
Now socket.io is trying to connect to http://example.org/socket.io
That dierectory does not exist. If anything, the proper path should be http://example.org/chat/socket.io
I have been looking all over the internet for a solution. There must be something fundamental or obvious about how nodejs/express operates that I am missing. Thanks a million!
Server.js - This is the file I start with node.
var express = require('express');
var path = require('path');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io').listen(http, { log: true, resource:'/socket.io/'});
app.use('/socket.io', express.static(path.join(__dirname,'/node_modules/socket.io/lib/')));
app.use('/bootstrap', express.static(path.join(__dirname,'/node_modules/bootstrap/dist/')));
app.use('/', express.static(__dirname));
var server = app.listen(8000);
io.sockets.on('connection', function(socket) {
console.log('A user connected!');
})

node.js /socket.io/socket.io.js not found

i keep on getting the error
/socket.io/socket.io.js 404 (Not Found)
Uncaught ReferenceError: io is not defined
my code is
var express = require('express'), http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
and
<script src="/socket.io/socket.io.js"></script>
what is the problem ???
any help is welcome!
Copying socket.io.js to a public folder (something as resources/js/socket.io.js) is not the proper way to do it.
If Socket.io server listens properly to your HTTP server, it will automatically serve the client file to via http://localhost:<port>/socket.io/socket.io.js, you don't need to find it or copy in a publicly accessible folder as resources/js/socket.io.js & serve it manually.
Code sample Express 3.x -
Express 3 requires that you instantiate a http.Server to attach socket.io to first
var express = require('express')
, http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
//...
server.listen(8000);
Happy Coding :)
How to find socket.io.js for client side
install socket.io
npm install socket.io
find socket.io client
find ./ | grep client | grep socket.io.js
result:
./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js
copy socket.io.js to your resources:
cp ./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js /home/proyects/example/resources/js/
in your html:
<script type="text/javascript" src="resources/js/socket.io.js"></script>
It seems that this question may have never been answered (although it may be too late for the OP, I'll answer it for anyone who comes across it in the future and needs to solve the problem).
Instead of doing npm install socket.io you have to do npm install socket.io --save so the socket.io module gets installed in your web development folder (run this command at the base location/where your index.html or index.php is). This installs socket.io to the area in which the command is run, not globally, and, in addition, it automatically corrects/updates your package.json file so node.js knows that it is there.
Then change your source path from '/socket.io/socket.io.js' to 'http://' + location.hostname + ':3000/socket.io/socket.io.js'.
... "You might be wondering where the /socket.io/socket.io.js file
comes from, since we neither add it and nor does it exist on the filesystem. This is
part of the magic done by io.listen on the server. It creates a handler on the server
to serve the socket.io.js script file."
from the book Socket.IO Real-time Web
Application Development, page 56
You must just follow https://socket.io/get-started/chat/ and all will work.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, function(){
console.log('listening on *:3000');
});
If you are following the socket.io tutorial https://socket.io/get-started/chat/, you should add this line as below.
app.use(express.static(path.join(__dirname, '/')))
This is because in the tutorial, Express will only catch the url
/ and send the file of index.html.
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
However, in the index.html, you have a script tag (<script src="/socket.io/socket.io.js"></script>) requests the resouce of socket.io-client, which is not routed in index.js (it can be found in console-network that the url is http://localhost:3000/socket.io/socket.io.js).
Please check the directory path mentioned in your code.By default it is res.sendFile(__dirname + '/index.html');
make sure you index.html in proper directory
Steps to debug
npm install socket.io --save in static files (index.html) for example, you may have installed it globally and when you look at the debugger, the file path is empty.
Change your script file and instantiate the socket explicitly adding your localhost that you have set up in your server file
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
<script>
const socket = io.connect("localhost:5000");
$(() =>
Double check that the data is flowing by opening a new browser tab and pasting http://localhost:5000/socket.io/socket.io.js you should see the socket.io.js data
Double check that your server has been set-up correctly and if you get a CORs error npm install cors then add it to the server.js (or index.js whatever you have chosen to name your server file)
const cors = require("cors");
const http = require("http").Server(app);
const io = require("socket.io")(http);
Then use the Express middleware app.use() method to instantiate cors. Place the middleware this above your connection to your static root file
app.use(cors());
app.use(express.static(__dirname));
As a final check make sure your server is connected with the http.listen() method where you are assigning your port, the first arg is your port number, for example I have used 5000 here.
const server = http.listen(5000, () => {
console.log("your-app listening on port", server.address().port);
});
As your io.on() method is working, and your sockets data is connected client-side, add your io.emit() method with the callback logic you need and in the front-end JavaScript files use the socket.on() method again with the call back logic you require. Check that the data is flowing.
I have also edited a comment above as it was the most useful to me - but I had some additional steps to take to make the client-server connection work.
If you want to manually download "socket.io/socket.io.js" file and attaché to html (and not want to get from server runtime) you can use https://cdnjs.com/libraries/socket.io
like
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js" integrity="sha512-eVL5Lb9al9FzgR63gDs1MxcDS2wFu3loYAgjIH0+Hg38tCS8Ag62dwKyH+wzDb+QauDpEZjXbMn11blw8cbTJQ==" crossorigin="anonymous"></script>
while this doesn't have anything to do with the OP, if you're running across this issue while maintaining someone else's code, you might find that the problem is caused by the coder setting io.set('resource', '/api/socket.io'); in the application script, in which case your HTML code would be <script>type="text/javascript" src="/api/socket.io/socket.io.js"></script>.
If this comes during development. Then one of the reasons could be you are running a client-side file(index.html). But what you should do is run your server(example at localhost:3000) and let the server handle that static file(index.html). In this way, the socket.io package will automatically make
<script src="/socket.io/socket.io.js"></script> available on the client side.
Illustration(FileName: index.js):
const path = require('path');
const express = require('express');
const socketio = require('socket.io');
const port = 3001 || process.env.PORT;
const app = express();
const server = http.createServer(app);
const io = socketio(server);
//MiddleWares
app.use(express.json());
app.use(
express.urlencoded({
extended: false,
})
);
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile('index.html');
});
io.on('connect', (socket) => {
console.log('New user joined');
}
server.listen(port, () => {
console.log(`App has been started at port ${port}`);
});
After this run your server file by the command
node index.js
Then open the localhost:${port}, Replace port with given in the index.js file and run it.
It solved my problem. Hope it solves yours too.

Directory-Dynamic Node.JS express server

I am new with the whole web-server side of Node.JS,
Unfortunately I cannot find how to make my express server serve dynamic web pages.
I understand routes, and how they work.
Here's my code
var express = require('express');
var app = express();
app.get('/', function (req, res){
res.send('Hello There From Express!\n');
});
app.listen('200');
This will only server the / directory, everything else will fail.
How would i set this up where it will serve a dynamic webpage range,
So like if the user wanted to type in http://example.com/billing.html,
it would redirect to the billing.html file.
I don't want to have to put in a routing line for each page, I would like to be able to just dynamically serve webpages..
Sorry if i'm not making any sense, i'm not the best at asking questions.
If you are wanting to just have express serve a folder of static HTML files without dealing with each one individually, you could define your app as:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/html')); //where /html is a subfolder of your app
app.listen('200');
with /html containing all of your static files.

Categories