Menu
CoddyTech

Hello, Express

Part of the Express Basics section of Coddy's Node.js journey. Lesson 1 of 23.

A web server waits for requests from browsers and apps and sends back responses. Express is the most used library for writing one in Node.js.

import express from 'express';

const app = express();

app.get('/hours', (req, res) => {
    res.send('Open 9 to 5');
});

app.listen(3000);

app.get('/hours', ...) is a route: what to do when someone asks for the path /hours with a GET request. GET is the kind of request a browser sends to open a page. Express calls the function with the request req and the response res, and res.send sends the answer. Nothing goes back until it is called. app.listen(3000) starts the server on port 3000.

On a laptop you would start it with node server.js and call it from a browser or with curl. Here Run starts it and the request bar sends the requests.

challenge icon

Challenge

Easy

Recipe Box needs a home page that greets visitors.

  1. In server.js, change the route for / so it sends the text Welcome to Recipe Box instead of Hello from Express!. Send exactly that text, with no full stop.

Try it: Press Run. Type / in the request bar and press Send. This sends a GET request, the kind a browser sends when it opens a page. You should see Welcome to Recipe Box with status 200. Then send /nope. No route has that path, so Express itself responds with status 404 and a page that says Cannot GET /nope.

Try it yourself

import express from 'express';

const app = express();

app.get('/', (req, res) => {
    res.send('Hello from Express!');
});

app.listen(3000, () => {
    console.log('Recipe Box is running on port 3000');
});

All lessons in Express Basics

Practice on your own: Express playground