transferring node app to server - javascript

I have a node server file, app.js which uses express.
The file looks like this
var express = require('express')
var app = express();
app.use(express.static(__dirname + '/public'))
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
If I run $ node app.js from my terminal it launches and if I navigate to localhost:3000 on my machine I see Hello World!.
I have uploaded the file to a server and try and navigate to the index.html file , which is in the public folder, however it doesn't work.
Maybe I am missing many steps, but can anyone advise how I can launch the node app on my server?

Your server doesn't send index.html anywhere. It only serves "/" path by sending text "Hello World!".
With Node.js, you have to tell which content you want to send for each route.
You can simply send the specific file : (sure, but dirty)
app.get('/index.html', function (req, res) {
res.send(PATH_TO_FILE/index.html);
});
Or specify which path to use to serve files by default :
app.use(express.static(__dirname + '/public'));
And you put all your public files to serve automatically in the public folder :
YOUR_PROJECT/public/AUTOMATICALLY_SERVED_FILES
Where AUTOMATICALLY_SERVED_FILES can be index.html or css/style.css for exemple.
NB : NGINX is not useful at this point.

On the server, nodejs is configured right?
I use forever with nodejs, it is useful if you would like to use nodejs like a service on linux base system.

Related

How do you use hyperlinks with a Node.js web server?

I'm trying to send different html files to users, with index.html being a bunch of hyperlinks that a user can click on to see that file, but I get an error that says "cannot GET (that file's name)" whenever I click on a hyperlink.
var app = require('express')();
var http = require('http').createServer(app);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Here's my index.html:
<html>
Pong Game
</html>
You can define a public static file folder like this:
app.use(express.static(__dirname + '/public'));
Everything you have in your public folder will be accessible at the root of your URL (i.e. /pongClient.html)
Basically you have to setup the node server so that it knows where to get the file from and You can setup a static server in this case. The syntax in express can be found here
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
var app = require('express')();
var http = require('http').createServer(app);
app.use(express.static(__dirname)) //since the index.html and probably pongClient.html are in the current directory based on your code.
http.listen(3000, function(){
console.log('listening on *:3000');
});
Nodejs has nothing to do with hyperlink. But if you want your user to access different page use
app.get('/', function(req, res){
res.send('<p>Pong Game</p>\n');
});
The port number is 80(I am assuming your web server port is 80).Mainly you have to give full URL(accessible ones).

Cannot GET /blah.html - .ejs can't load html?

I'm using Nodejs and Express to create a dynamic webpage.
I have a home.ejs file that has this iframe:
<iframe id="newstable" src="/news_tables/2018-08-04.html" height="1000" width="100%"></iframe>
My folder directory is:
News_Aggregator (includes app.js)
News_Aggregator/news_tables (includes a bunch of html files, e.g. `2018-08-04.html`)
News_Aggregator/views (includes my `home.ejs` file)
And my app.js:
const express = require('express');
const app = express();
app.set("view engine", "ejs");
app.get('/', function(req, res){
res.render('home.ejs');
});
app.listen(8000, () => {
console.log('Example app listening on port 8000!')
});
However, when home.ejs is rendered, my iframe doesn't load the html page:
This works in "normal" HTML. What am I missing to get the .ejs file to find this and render correctly?
You get the error because the server dosen't know where to get the files from.
First You must define where the static .ejs files will be. Lets say something like this. if your files are in a public folder(ejs,css etc) and you will get them from there. Setup both with:
app.use(express.static(__dirname + '/public'))
app.set('views', path.join(__dirname, '/public'));
from here you can just in your response if you have a home.ejs file
res.render('home', {});
You should look over Express static() from here and learn how to serve files
The fact your HTML is generated from a .ejs file is irrelevant.
Your HTML says the browser should ask the server for the URL /news_tables/2018-08-04.html.
Your HTTP server has a route app.get('/', and no other routes.
Your HTTP server doesn't know about the URL /news_tables/2018-08-04.html, so it returns a 404 Not Found.
You need to write code which will serve up all the URLs you want it to.
You should probably look at the Express static() middleware if you want to serve static files.
The only thing that works is removing ".html" from address "localhost:3000/index.html".

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.

How do I include an external JavaScript file when serving an HTML file with a response object in expressjs?

My express app serves an HTML page from my disk upon the initial GET (i.e., if I hit "http://localhost:3000/" in the browser). Now I would like to access a JavaScript file which is in the same location in the disk as the HTML file. When I try to include it in 'index.html' by using
<script src="/myJavaScriptFile.js" type="text/javascript" ></script>
or
<script src="./myJavaScriptFile.js" type="text/javascript" ></script>
or
<script src="~/MyAbsolutePath/myJavaScriptFile.js" type="text/javascript"</script>
it doesn't work. The myJavaScriptFile.js file is never reached.
My express app looks like this:
var express = require('express')
var testMethod = require('./test')
var app = express()
app.use(bodyParser.urlencoded({ extended:false }));
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
app.get('/', function (req, res) {
console.log('In /');
res.sendFile(__dirname + '/index.html');
})
Express app is serving 'index.html' using the reference path '__dirname' + '/index.html' using res.sendFile function. (I am beginning to feel that this is a bad way of doing it. Please let me know if you think so too).
Also as we can see in the express app, an external JavaScript file called 'test' which is in the same location as 'index.html' and 'express.js' is being included without any issues. Could anyone please shed light on what's actually happening in the background? What exactly would be reference path for the JavaScript file that I can give in my 'index.html' if it is being served by express app? Thank you.
Serving files, such as images, CSS, JavaScript and other static files is accomplished with the help of a built-in middleware in Express - express.static.
Pass the name of the directory, which is to be marked as the location of static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this:
app.use(express.static('public'));
Now, you will be able to load the files under the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
More Detail Here
Happy Helping!

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.

Categories