Routes

Any web server needs to define some routes that can serve data or html.

Express makes this easy with their app.METHOD functions.

for example to make a basic hello world endpoint for '/' is as simple as the following:

alt

JS

Copy

app.get('/', function (req, res) {
  res.send('Hello World')
})

The response headers look like this:

response headers

Copy

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 13
ETag: W/"d-CgqfKmdylCVXq1NV12r0Qvj2XgE"
Date: Tue, 11 Mar 2025 11:08:30 GMT
Connection: keep-alive
Keep-Alive: timeout=5

It's worth noting that the response is text/html.

To send json, we can send a JavaScript Object, and express will automatically send it as JSON

JS

Copy

app.get('/', function (req, res) {
  res.send({data: 'Hello, World!'})
})

And we get the following response header with:

response headers

Copy

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 23
ETag: W/"17-xg7n2mUBd4HGLClPS5+0NqvUK4k"
Date: Tue, 11 Mar 2025 11:14:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5

Query Parameters

Query parameters are often used for searching, as it enables users to share links to a specific search.

To access query parameters in express, we simply have to use the query object from the request object.

JS

Copy

app.get('/search', (req, res) => {
    res.send({data: req.query.q});
})

If we hit the endpoint:

/serach?q=hello

Copy

{
"data": "hello"
}

Path variables

Path variables is a key aspect of any REST API, and can be defined with '/:name'

JS

Copy

app.get('/cars/:id', (req, res) => {
    res.send({data: req.params.id});
})

and if we hit the endpoint:

/cars/2 

Copy

{
"data": "2"
}

Parsing body as JSON

To parse a post request's body as JSON

We need to tell express to use its built-in json parser.

JS

Copy

app.use(express.json())

We can access the parsed body through the request's body 'req.body'

JS

Copy

app.post('/cars', (req, res) => {
    const body = req.body;
    res.send({data: body});
})