Confused about Express, node.js terminology - node.js

I am new to web development. I am currently learning express.js. The following chunk of code and text is from their documentation.
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
This app starts a server and listens on port 3000 for connections.
I am confused as to what the server is here. Which line of code refers to the 'creation of the server'? Is the express app the server itself, or is it only listening for requests on port 3000, while the server is something else?
Thanks a lot!

Basically Express is a framework of Node Js, Like Python has Django, Java has Spring etc..
When you create server in node js you use HTTP module, In express by inside function they provide listen function.
When you create Server using Node you use below code
http.createServer(function (req, res) {
res.write('Hello World!');
res.end(); //end the response
}).listen(8080);
So in node http module have Listen function & in express js express module have listen function.
app.listen creates a new server. In express there is no any terminology of CreateServer. So express is very much flexible to use.
Please follow this url http://expressjs.com/en/guide/writing-middleware.html

At the minute you call listen the server is going to start running, listening to the PORT you have defined.
Here is a line by line commented version of your code :
//We are creating the express app by setting it to the app variable.
const express = require('express')
//The express object
const app = express()
//The port
const port = 3000
/*
.get is telling to the express object that when it gets that route ('/')
it should give the specified response : 'Hello World!' for our case.
It takes in 2 arguments:
(1) the url - the route
(2) the function that tells express what to send back as a response for the
request - the callback function
*/
app.get('/', (req, res) => res.send('Hello World!'))
//.listen is going to bind the application to the port 3000.
app.listen(port, () => console.log(`My awesome app is listening at
http://localhost:${port}`))
To find out about the difference between the concepts node and express, I found this response usefull.

As you said, that entire chunk "create" the server, its not only one line to "create" the server.
Using node and npm you install express const express = require('express')
In this line yo use express framework const app = express()
In this line you set a port const port = 3000
In this line you create the main root app.get('/', (req, res) => res.send('Hello World!'))
and this line use the port and up runnig your web server app.listen(port, () => console.log(Example app listening at http://localhost:${port}))
As you can see, all of then combined "creates" the server

Related

Socket.io client requests fail when frontend and backend run on different ports

I want to use Socket.io with a React frontend and NodeJS & Express backend but have both running on different ports for development (Fontend: 3000; Backend: 8080).
When the Socket.io-Client has loaded my frontend executes var socket = io('http://localhost:8080'); and then automatically makes a GET request to http://localhost:8080/socket.io/?EIO=4&transport=polling&t=NSlH7of. That request should normally return something like 0{"sid":"XXX","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000} but the Chrome Dev Tools say that the status is (failed) net::ERR_FAILED. There also is no response available in the Dev Tools.
However when I run the GET request in my HTTP-Client it returns exactly what I expect it to return.
That error looks like it's caused by the Socket.io-Client but I get no error whatsover besides the failed GET request. When I run everything on one port (Frontend served with webpack by the backend) the request goes through as expected.
I would appreciate any help! Thanks!
server.js
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
//Serve static react app
app.use(express.static('dist'));
app.use('/app', express.static('dist'));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '../../../' + '/dist/index.html'));
});
io.on('connection', (socket) => {
console.log('Connected')
socket.on('join-game', (gameId, userId) => {
console.log(gameId, userId);
})
})
http.listen(process.env.PORT || 8080, () => {
console.log(`Listening on port ${process.env.PORT || 8080}!`);
});
I finally resolved the error!
The problem was that the request was blocked by CORS of Chrome.
I changed the line const io = require('socket.io')(http) to const io = require('socket.io')(http, { cors: {}});.
Now everything is working as it should.
If you want to hit port 8080 for your socket.io connection, you must set up a server for that port in your nodejs program (your back end). Code running in browsers (front-end code in React parlance) like your code
var socket = io('http://localhost:8080')
can only originate connection requests. And, if no server is listening for those requests, you get the failure status that your devtools showed you.
By the way, you'll be wise to make your nodejs server program use just one port. With just one port, it's much simpler to deploy to a production server.

In Express JS does app.listen need to be at the end of the file?

In most tutorials using Express JS the app.listen function is always added at the end of the file. I want to understand if this is essential as all middleware is run in sequence.
Most examples show:
const express = require('express)
const app = express()
app.get('/', (req, res) => {
res.send('Test')
}
app.listen(3000, () => {
console.log('Server running on port 3000')
}
Is there any reason this shouldn't be done:
const express = require('express)
const app = express()
app.listen(3000, () => {
console.log('Server running on port 3000')
}
app.get('/', (req, res) => {
res.send('Test')
}
I worked out the answer to this, in case anyone goes looking for it.
app.listen is effectively a wrapper function that calls HTTP.createServer.
From what I can understand createServer sets up an event listener on the event loop. When the operating system receives a HTTP request on the particular port being listened to, such as port 80, the req is processed by express.
Since createServer is an asynchronous operation it gets executed in the event loop once the main program is executed. Therefore it doesn't matter where this code is placed. It is at the end in most examples as a standard rather than technical requirements.

Express not loading in URL

I currently have an express server I'm running based on the express tutorial.
Here is my code for server.js
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
the server.js file is in a directory on my server:
http://myurl.com/node-webshot/server.js
I start the server with: npm start
and get this:
> webshot#0.18.0 start /home/myurl/node-webshot
> node server.js
Example app listening on port 3000!
when I go to my url: http://myserver.com/node-webshot/
I see the directory listing only:
note "myserver.com" is just a fill in to path for working folder.
My expected result would be that when I go to the roof of the file where server.js is loaded that it would show the "Hello world". Not sure what I'm missing here.

use different routes for different ports in express app

Is it possible in express/node app to have different routes configured to different ports?
Example:
'/foo/bar' accessible to only localhost:3000
'/bar/foo' accessible to only localhost:3002
Yes, but you just create two servers, each on its own port and then create an express app object for each server and register routes for the desired server on the appropriate app object. A given server only listens on one port.
const express = require('express');
// first server
const app3000 = express();
app3000.get('/bar/foo', function(req, res) {
// code here for port 3000 handler
});
app3000.listen(3000);
// second server
const app3002 = express();
app3002.get('/foo/bar', function(req, res) {
// code here for port 3002 handler
});
app3002.listen(3002);

Node.js server with http get json

I want to create a simple Node.js server to do the following :
With my application I just do the command http.get(Node.Js_Server_address/json) to get the json file data stored on my server.
Could please help me with a tutorial? Any help would be appreciated!
This is very simple example of node.js server:
var app = require('./app');
var http = require('http');
var server = http.createServer(app);
server.listen(8080, function() {
console.log("listening to: http://127.0.0.1:8080");
});
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
there is a nice tutorial here and here ...
you can use npm to install node.js and all the packages that you need for it.
hope it helps.
There are lots of examples on this topic, i think you should make some googling before next time.
You can create a REST server via express module of nodeJs. In your server folder use npm install express to download express module. You can get more information about express from here. After that create a server.js file in your server folder.In server.js
var express = require('express');
var app = express();
var PORT = 8080;
/* req stands for request, res stands for response */
app.get('/json',function(req,res){
res.json(yourData);
})
app.listen(PORT,function(){
console.log('Express is listening port:' + PORT + '!');
})
So this should do the work. Let me know if this helps you.

Resources