This content originally appeared on DEV Community and was authored by Eric The Coder
Here is a series of articles to help you create backend applications in Javascript.
Node.js is now a must, so it is essential for a developer to master it.
I will publish a new article every two days and little by little you will learn everything there is to know about Node.js
To not miss anything follow me on twitter: https://twitter.com/EricTheCoder_
The HTTP module
The HTTP module is a set of functions that allow you to create and manage your own web server.
Reminder: What is a web server?
A web server is a set of hardware and software that allow access to hosted files, web page and database stored on a computer.
The web server also consists of an HTTP server. HTTP server is software that understands / receives URLs and requests via the HTTP protocol (the protocol used by the browser to display web pages).
At the simplest level, whenever a browser needs a file or other hosted on a web server, the browser makes the request to the server (it is said to send an HTTP request). When the request reaches the server, the HTTP server processes it and returns the response.
In summary, the bottom line is that although an HTTP server may seem complicated, in fact it is just a succession of requests and responses. You will see here below that NodeJS allows you very easily to create an HTTP server and that it is very easy to read a request and send a response.
Creating an HTTP server with NodeJS
Here is an example of creating an HTTP server
const http = require('http')
const server = http.createServer((req, res) => {
// Send response
res.end('Hello World from the server')
})
server.listen(5000, 'localhost', () => {
console.log('Server is listening at localhost on port 5000')
})
Let's see line by line the different steps for creating a server
Loading the HTTP module
const http = require('http')
Server creation with a callback function. Note that there are two parameters that are passed to the function: req and res.
- req: will contain info on the incoming request
- res: will be used to define the outgoing response
const server = http.createServer((req, res) => {
// send the response
res.end('Hello World from the server')
})
res.end() tells the server that the response is complete and can now be sent
Starting the server. The server will wait and read the requests that arrive on port 5000.
server.listen(5000, 'localhost', () => {
console.log('Server is listening at localhost on port 5000')
})
This is an endless loop. Each time a request will be sent to our server at port 5000 (ex: localhost:5000), the server will execute the callback (see previous code block) and therefore in this case send the response 'Hello World from the server'
If you want to test this server, launch the application
$ node app.js
Server is listening at localhost on port 5000
Open your browser and visit localhost:5000
The message 'Hello World from the server' should display in your browser
In fact if you visit any page ex: localhost: 5000/about the same message will always be displayed.
It is possible to read the url path of the request ex: /about or /home etc. and return a different response depending on the path.
The path information is included in the request.
To read information about the request we will use the 'req' object. which as you know contains all the information of the request.
Specifically, the url path is in the 'req.url' property
Here is an example of a small HTTP server which, depending on the url received, displays a different page
const http = require('http')
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.end('<h1>Home page</h1>')
} else if (req.url === '/about') {
res.end('<h1>About page</h1>')
} else {
res.end('page not found')
}
})
server.listen(5000, 'localhost', () => {
console.log('Server is listening at localhost on port 5000')
})
HTTP Headers
HTTP Headers allow the client and the server to pass additional information along with the request or response.
For example, the Header of a request could contain the format of its content ex. HTML or JSON and / or related information for user authentication.
Response Header example
To add a header to the response, we need to add a function before the res.end() function
res.writeHead(404, {
'Content-type': 'text/html'
})
res.end('<h1>Page not found</h1>')
The writeHead function allows you to specify the content type of the message, either 'text/html'
When running the res.end() function NodeJS will include the Header to the response.
Your first HTTP server
Voila, you have created your first HTTP server. Although this is a very basic server for the moment, remember that an HTTP server is simply a succession of requests and responses.
So, in its simplest form, your web application will do just that. That is to say, process requests and return responses.
Introduction to ExpressJS
Although NodeJS allows us to create our own HTTP server, to create a real web application we would have to code hundreds or even thousands of lines of code in order to handle all the possibilities and all the exceptions.
Fortunately for us there are several NodeJS libraries / frameworks that do this job for us.
The most popular of all is ExpressJS. ExpressJS is a framework (set of libraries) designed with NodeJS in order to greatly simplify web application development.
So we will see in detail later how to use ExpressJS in our NodeJS applications.
Conclusion
That's all for today, follow me on twitter: https://twitter.com/EricTheCoder_ to be notified of the publication of the next article (within two days).
This content originally appeared on DEV Community and was authored by Eric The Coder
Eric The Coder | Sciencx (2021-10-07T12:00:32+00:00) Create a backend in Javascript (part 4): Create your first HTTP Server. Retrieved from https://www.scien.cx/2021/10/07/create-a-backend-in-javascript-part-4-create-your-first-http-server/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.