Categories
Express JavaScript Answers

How to Get the Hostname of the Current Request in Express?

To get the hostname of the current request in Express, we can use the req.headers.host property.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send(req.headers.host);
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to return the hostname of the client that made the request as the response for the / route.

The hostname is a string.

Therefore, when we go to / , we see the hostname of the client that made the request returned.

Categories
Express JavaScript Answers

How to Programmatically Send a 404 Response with Express?

To programmatically send a 404 response in our Express app, we can use the res.sendStatus or res.status methods.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) =>{
  res.send('hello world');
});

app.get('*', (req, res) => {
  res.sendStatus(404);
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to call sendStatus with 404 in the * route, which is run whenever a request is received from a URL that isn’t picked up by any other route.

We can also write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('hello world');
});

app.get('*', (req, res) => {
  res.status(404).send('Not found');
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to call res.status with 404 to send a 404 response.

Then we call send with 'Not Found' to send it with a body.

Categories
Express JavaScript Answers

How to Set the Response Header on Express.js Responses?

To set the response header on express.js responses, we can call the res.set method with the response header content.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res
    .set({
      'Content-Type': 'text/plain',
      'Content-Length': '123',
      'ETag': '12345'
    })
    .send('hello world');
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to call the set method in the / route with an object that has the response header keys and values.

The property names are the keys and the property values are the values.

Then we can also call send with the response body we want to return.

Therefore, when we make a request to the / route, we should see hello world in the response body and the object’s content in the response header.

Categories
Express JavaScript Answers

How to Set Response Status and JSON Content in a REST API Made with Node.js and Express?

To set response status and JSON content in a REST API made with Node.js and Express, we call the res.status method with the HTTP status code that we want to return.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('hello world');
});

app.get('/error', (req, res) => {
  res.status(500).send({ error: "error" });
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We add the /error route, which returns a 500 response by call res.status with 500.

Then we call send with an object to return that as the JSON response body.

Categories
Express JavaScript Answers

How to Redirect 404 Errors to a Page in Express.js?

To redirect 404 errors to a page in Express.js, we can add a route that accepts requests from all URLs that haven’t been handled by other routes.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) =>{
  res.send('hello world');
});

app.get('*', (req, res) => {
  res.send('not found', 404);
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to add a route that handles all routes that aren’t the / route with:

app.get('*', (req, res) => {
  res.send('not found', 404);
});

The asterisk indicates that this route is a catch-all route that handles any requests from URLs not handled by other routes.

Therefore, when we go to / , we see hello world .

Otherwise, we see not found .