Categories
Express JavaScript Answers

How to Set Cookies in Node Apps that Use the Express Framework?

To set cookies in Node apps that use the Express web framework, we can use the res.cookie method to set the cookie.

res.cookie will be available once we add the cookie-parse package into our app, which we can install by running:

npm i cookie-parser

For instance, we can write:

const express = require('express')
const cookieParser = require('cookie-parser');
const app = express()
const port = 3000

const options = {
  maxAge: 1000 * 60 * 15,
  httpOnly: true,
  signed: true
}

app.use(cookieParser('secret'));

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

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

We add:

app.use(cookieParser('secret'));

to add the cookieParser middleware.

The argument is the secret.

Then to add the cookie to the response of the / route, we call res.cookie with the cookie key, value, and options respectively.

maxAge is the duration that the cookie lasts.

httpOnly set to true makes the cookie accessible only by the webserver.

signed set to true indicates that the cookie should be signed with a secret.

Now when we make a request to the / route, we get the cookie back in the response.

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.