02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Configuring a Basic Server in Node.js

Configuring a Basic Server in Node.js

In this tutorial, we will learn how to configure a basic server in Node.js. Setting up a server is a fundamental step in building web applications, and understanding how Node.js handles incoming requests is crucial for creating scalable applications. This tutorial, originally created in 2016, includes some updates to keep it relevant for current development practices.

Step 1: Loading the HTTP Module

Node.js has a built-in module called http that allows us to create and configure servers. To start, we need to load this module using the require function.

Example: Loading the http Module

const http = require('http');

The http module provides several functions that make it easy to create a basic web server. Using this module, we can build a server that listens for incoming requests and sends responses.

Step 2: Creating the Server

After loading the http module, we can use it to create a server using the createServer method.

Example: Creating a Server

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, Node.js Server!\n');
});

In the above code:

  • req: Represents the incoming request.
  • res: Represents the response we send back to the client.
  • res.statusCode = 200: Sets the status code to 200 (OK).
  • res.setHeader('Content-Type', 'text/plain'): Sets the content type to plain text.
  • res.end('Hello, Node.js Server!\n'): Ends the response and sends back the string 'Hello, Node.js Server!'.

Step 3: Defining the Port and Hostname

To make the server accessible, we need to specify the hostname and port on which the server will listen for requests.

const hostname = '127.0.0.1';
const port = 3000;
  • hostname: Represents the IP address of the server (in this case, 127.0.0.1, which refers to localhost).
  • port: Represents the port number the server will listen to. Here we use 3000.

Step 4: Starting the Server

To start the server, we use the listen method, passing in the port and hostname.

Example: Starting the Server

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

When the server starts, it will print a message in the console indicating that it is running and where it can be accessed.

Step 5: Testing the Server

To test your server, navigate to http://127.0.0.1:3000/ in your web browser. You should see the message 'Hello, Node.js Server!' displayed on the page.

Tip (2024 Update): Node.js now supports using ES Modules. You can replace require with import if you use an .mjs file extension or set "type": "module" in package.json.

Step 6: Stopping the Server

To stop the server, press CTRL + C in the terminal where the server is running.

Conclusion

In this tutorial, we have successfully configured a basic server in Node.js using the built-in http module. We learned how to create and start a server, define the hostname and port, and handle basic requests and responses.

This foundational knowledge will be valuable as we move on to more complex server configurations, routing, and connecting to databases. With this understanding, you are ready to build more interactive and dynamic web applications using Node.js.

Video Transcript

00:00As we mentioned previously, one of the core competencies
00:03of node js is its capability of being a server.
00:07And that's exactly what we're gonna look at at this lecture.
00:10Although I wanted to say a small stipulation
00:12that generally speaking,
00:14you're not gonna be running directly a server
00:16with native node JS code.
00:19Part of the philosophy of node js is to be, you would say,
00:23like dumb to how do does the developer work with it?
00:26And in other words, the idea itself is for us
00:29to depend on packages that we like that will sit
00:32above the node js enabling us to create
00:36a server in the way that we like.
00:38And we're gonna take a deep look into
00:39that in the next chapter, which a whole chapter is gonna be
00:42dedicated to one specific package that is gonna be used
00:46to provide us server functionalities.
00:49But for now in this lecture, what we're gonna go ahead
00:51and do is get you familiar with the process
00:53of creating a server from scratch
00:56as we integrate into it some of the new EMCA script, um,
01:02into the production.
01:03And by the way, you don't have to,
01:04and this is part of your privileges,
01:07especially if you're gonna go into production
01:08and you're not gonna use a version of no JS
01:11that supports this latest version of JavaScript,
01:13then just don't use the latest version of JavaScript.
01:16We'll talk briefly about that in this lecture,
01:18but by the end of this lecture you're going
01:20to know the basics of how to set up
01:22and how to configure a server using node js.
01:28So far in our work, we were working
01:30with basically the creation process
01:32that did not involve any server,
01:34but end of the day, no JS is all about a server as well,
01:38a really powerful server
01:39that runs on IO in out input output.
01:42Very, very smart stuff.
01:44A lot more interesting than a lot
01:46of the other traditional server side languages
01:48beyond the fact that we're working in JavaScript.
01:50But really in essence, we really want to have a server.
01:53We want to see something on a server.
01:54And for that intention is this lecture.
01:57So what I want you to do is I want you
01:59to go into the index dot js file of your application,
02:03the one where we were playing around
02:05with the IS array package.
02:07And I wanna show you basically the process of creating
02:10and working with node js.
02:14Now we've sort how to work with require already
02:16and one of the required that are built in that we don't need
02:19to preload anything, we don't need to load
02:22or install any packages is the HTTP
02:25that are many different packages
02:26and many different modules that are available,
02:29which you could find in the documentation.
02:32Now with required, just like with the IS array, not contrary
02:35to other server side languages, that once you load them up,
02:38then they already have a name.
02:40Once you load a package, it does not have a name
02:42until you assign a name to it.
02:44Like we've done it with this variable in this case
02:47because we're only gonna use require only use HTT P once,
02:52we don't really need to create a name.
02:53And instead of that we could just directly start working
02:56with the value that came back, that
02:58HTTP object that doesn't really have a name
03:01'cause we didn't assign a name to it.
03:03And what I wanna do is I want to create a new server
03:06by calling the create server, which is a method that is one
03:10of the methods that come back from the HTTP module.
03:14Now I wanna show you also another something really cool
03:16that was introduced into ecma Script six
03:20and onwards, which enables us, instead of writing here
03:23for our callback function to type in the function name
03:25and its parameters and open a curly bracket
03:28and close a curly bracket, instead of that, we could get rid
03:31of the word function and in between the parameters
03:35and that curly bracket to put an arrow,
03:38this shortcut is called an arrow function.
03:41Now, on parameters, I'm just gonna give them a better de
03:43descrip descriptive name
03:44because we're gonna have two parameters, a request
03:47and a response object, which we,
03:48which we could then manipulate and work with.
03:51In this case, what I really want
03:53to do is anytime a request comes to my server, I want
03:56to tell everyone I wanna respond, saying first of all,
03:59everything is completely fine by saying,
04:02by sending in the status code of 200 says
04:05that there are no errors, everything is good.
04:08The next thing I want to do is I want to tell the
04:10whoever's asking, I want to tell it that the type of content
04:16that is being sent that I'm sending, the type of content
04:19that I'm sending is plain text.
04:21So that way the browser will know that it should expect text
04:24and not an image or a video or any other type of content.
04:28Last but not least, we're gonna go ahead
04:30and send the actual content as we call the end function.
04:34And here we're gonna send in some sort of a string.
04:37Now just to make things a little bit more interesting
04:39and make our server just a tad more complex,
04:42I'm gonna go ahead and grab all
04:43of these variable definitions and I'm just gonna go ahead
04:46and set them up in the beginning.
04:48There's the tradition of inside of a function.
04:50You always start it up with the variable definitions.
04:53You always start with the, that's how I like doing it.
04:56And here I'm gonna call this.
04:57Um, alright, so this is s
04:59and I'm, I'm gonna another create another
05:00function, sorry, another string.
05:02I'm gonna call it out. And here I'm gonna put here
05:05a low world from node js
05:10and I'm gonna put here, uh, HR tag and H TM L HR tag.
05:15Now next I'm gonna go ahead and just into my out.
05:18I'm just gonna, instead of sending this to the console,
05:20I'm just gonna go ahead and add here with a line break in
05:24between each, each new line.
05:28And I'm just gonna go ahead here
05:29and mimic the exact same thing and just create it again.
05:34Oso for our array, oso for our string line.
05:37That is, and I've created the content that I want to have
05:41inside of my application.
05:43All that's left for me to do is to send out with my,
05:45out into the end, send that string out
05:48and I have a running server.
05:50Now, last but not least, I wanna do one more thing
05:52before we go ahead and test this out.
05:54And what I wanna do is I want to go ahead and also listen to
05:57and define what is the server
05:59that is actually going to be running.
06:02So I'm gonna go ahead
06:03and to be able to do that, what I really need right now is
06:06to also capture the server that has been created
06:09so I could then address it
06:10and tell it what are you listening for?
06:12Where, when will you be working?
06:14So to do that, I want to create a new constant
06:17and I'm gonna call it server.
06:18And I'm gonna assign it the value
06:20that comes back from the creation of our server.
06:23Now the reason why I'm using a constant is
06:25because this server is never changing.
06:27Once it's created, we're never changing the server object.
06:30So I feel comfortable using a constant.
06:32If you don't, you could, you could create it
06:35as a variable as well.
06:38So I'm gonna call with my server.
06:39The last thing that's left for me to do is to listen in
06:42to the specific port
06:43and host name that I really want to use.
06:46In this case, what I really want
06:47to use is I want to use the port.
06:49Which port do I want to use?
06:51I'm listening to Port 300, what, 3000, sorry,
06:55because this is gonna be a port
06:57that my local system is not actually using.
07:00And I'm gonna go ahead
07:01and also define my local host, which is in numbers
07:051 27 0 0 1.
07:07This will obviously only work locally.
07:09Last but not least, I'm gonna also add here a callback
07:13function that looks very similar to the callback function
07:15that we saw up here when we were creating a server.
07:18Only this time it has no parameters,
07:20but we're also going to use that arrow callback function.
07:24And I'm just gonna go ahead and use a console console log.
07:31I'm running and I'm gonna go ahead and save this.
07:35And once I save this, all that's left for me to do is O2.
07:39Go ahead and run it. So I'm gonna go into my terminal
07:41and I'm gonna go ahead
07:43and call my index file again with node.
07:45So let's take a look at this error
07:47and when one is,
07:48we're not seeing an error in our code itself,
07:50but we are seeing that we have an error that
07:53listened and used.
07:54This is already being used
07:56'cause I, I've been testing it out already previously
07:58and I must have take taken over that port already.
08:01So let's go ahead and enter our code
08:02and just change that port to let's say 3001.
08:06And I'm gonna go ahead and run it one more time.
08:09So if I go here, let me just clean things up
08:11and run it one more time and hopefully there we go.
08:13We're running. So now that our application is running,
08:16we could go ahead into our browser.
08:19And in our browser we could approach our, uh, ip,
08:22our local host with that IP that configured
08:25that actually worked for you that didn't throw an error.
08:27And if we run it, we're gonna see hello world from no
08:30js, blah, blah, blah, blah.
08:32So we could see that we are using
08:34and we are getting those vine breaks.
08:36The only problem that we have here is
08:37because we're sending plain texts,
08:39we're not getting real HTML
08:41and that's why the lines are not breaking as we would hope
08:44for it to break, which is fine
08:46because that is the situation that we've created.
08:48We, we just created a very simple, simple,
08:51simple server at this stage.
08:53In the next lecture, it's time
08:54For us to actually work with static files
08:57and see how do we serve up actually full files
09:00and not only dynamic content that is being created
09:03that will be sent on every single call to our server.
09:06So right now, if I just add your cat,
09:07it's gonna still send us back.
09:08As long as we're inside of this port, it's gonna send us.
09:11So if we go to a different port then it's
09:13not gonna give us anything.
09:14But we're, if we're in the right port, no matter
09:16what we send here afterwards is gonna give us the same
09:18thing, which is probably not that useful as a real server.
09:22Anyways, we need a little bit more on top of that.
09:26In this lecture we created a basic server using the native
09:29capabilities of node js.
09:31The next lecture we're gonna take our attention away from
09:35just creating it natively
09:36to depending on third party solutions that we could find
09:40through NPM.
09:42So in the next lecture we're gonna use HTTP server
09:44as a quick way to create a very simple solu solution
09:48for a server.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!