Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Setup a Web Server in Node.js using Express


    In this lesson, we build a very simple Express server. This server will have a single route that displays the current date and time and a handler for 404 pages.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: To build your first Express server, the first thing you need to do is to require Express. In order for your code to be able to use it, you need to install it using npm. We can open a terminal to npm install Express, and all the files should be included now.

    We'll go back to our code. We'll declare a new constant app which will use the Express library that we've just included. We'll also declare a new constant for the port number. We'll use 8888 for now.

    Then we can do our first route. We'll use app.get, and we'll specify the name of the route. In this case, we're using status, and it takes a callback which has a request and a response as parameters.

    For this route, we will return to local time. We'll start by declaring the local time in a constant. We'll just use a new date, and we'll use the to local time string.

    Now we can start building our response. We'll give it a status of 200, which is a success code. We'll send simply a string which says, "Server time is," and we'll use the local time which we've just defined.

    Let's also add a catchall route. We'll just use star, which means any route that wasn't defined already.

    It also takes a callback with a request and response. We can build our response here, and it will simply sense that as 404, or page not found.

    Finally, we'll use app.listen to initialize our server. It'll take a port -- which we've defined earlier -- as a parameter, and a callback for on success.

    We'll simply say server is running on port, and we'll specify the port number here. You now have your first express server.

    If we go back to our terminal, we can start the server by using Node. We've got our server running.

    Now if we go through our browser window, we can type in the localhost, 8888. We'll get a page not found because that route was not defined.

    We can use /status to get the server time, and any other page will give us a 404 error. That's it. You've got your first Express server up and running.