Reputation: 39
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!
Upvotes: 1
Views: 231
Reputation: 77
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.
Upvotes: 1
Reputation: 111
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
Upvotes: 4
Reputation: 260
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
Upvotes: 0