Categories
Express JavaScript Answers

How to Get Express to Output Nicely Formatted HTML?

To get Express to output nicely formatted HTML, we can set the app.locals.pretty property to true .

For instance, we can write:

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

if (app.get('env') === 'development') {
  app.locals.pretty = true;
}

app.set('view engine', 'pug')

app.get('/', (req, res) => {
  res.render('index', { title: 'Hey', message: 'Hello there!' })
});

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

to prettify the HTML code returned by the Pug template engine in the dev environment with:

if (app.get('env') === 'development') {
  app.locals.pretty = true;
}

We render the response with:

res.render('index', { title: 'Hey', message: 'Hello there!' })

title and message are variables that are interpolated into the template.

In views/index.pug , we have the following template code:

html
  head
    title= title
  body
    h1= message

Now when we view the raw response, we should get:

<html>
  <head>
    <title>Hey</title>
  </head>
  <body>
    <h1>Hello there!</h1>
  </body>
</html>
Categories
JavaScript Answers Nodejs

How to Move Files in Node.js Apps?

To move files in our Node.js apps, we can use the fs.rename method.

For instance, we can write:

const fs = require('fs')

const oldPath = 'old/file.txt'
const newPath = 'new/file.txt'

fs.rename(oldPath, newPath, (err) => {
  if (err) throw err
  console.log('Successfully renamed - AKA moved!')
})

to import the fs module with:

const fs = require('fs')

Then we specify the oldPath and newPath to set the source and destination file paths respectively.

Next, we call fs.rename with the oldPath and newPath to move the file from oldPath to newPath .

The 3rd argument is a callback that will be run when the file moving operation is done.

If there’re any errors, then err will be defined.

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.