Create a server using Node JS Native Javascript
Hello, in this post I want to share with you how to create a simple server on your local host.
Background
In this case, I’m on learning Javascript backend, there are 2 ways to native and use the framework Ekspress JS, I want to give a tutorial for those who all read this article
Task
create a server locally with the Javascript language
Getting Started
the first step is you need to make an index.js file and call a module/library Https, the code is just like this const http = require('http')
. this method "require" is calling the HTTP method, the "HTTP is a built-in library in Node JS, so you can only call it on your code.
then to create a server, the code can be like below
const http = require('http')
const listener = http.createServer((req, res) => {
console.log('req.headers.autorization', req.headers.authorization)
if (req.url === '/user'){
res.writeHead(200, {'Content-Type': 'application/json'})
res.end(JSON.stringify({ name : 'John Doe'}))
} else {
res.writeHead(200)
res.end('Hello World')
}})listener.listen(8000, 'localhost', () => {
console.log('Server is listening on port 8000')
})
the method http.createServer
have the callback parameter req and res, as we know req for a request and res for a response. if we want to make a routing in native node JS we can use if (req.url === '/user')
. it is just an example for /user. if we run it will show name: 'John Doe'
and for "else" or other it will show 'Hello World'
And we can run in terminal command bash with node index.js
. And then notice will prompt on the terminal "Server is listening on port 8000". We can see on our browser on locallost:8000. We have already succeeded to build a server with native node JS, the preview is below.
okay thanks for your read, see you in the next post :)
Github :https://github.com/Hendra-Kusuma
Email : hendrakusuma.vegas@gmail.com