Categories
Express JavaScript Answers

How to Get Raw Request Body with Express?

To get raw request body in our Express app, we can add the raw body parsing function and set that as the value of the verify option of the middleware.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser');

const rawBodySaver =  (req, res, buf, encoding) =>{
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
  }
}

const options = {
  verify: rawBodySaver
};

app.use(bodyParser.json(options));

app.post('/', (req, res) => {
  console.log(req.rawBody)
  res.send('hello world')
});

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

We have the rawBodySaver function that gets the buf parameter, which has the raw request body buffer.

Then we call toString on it with the encoding and assign that to the req.rawBody property.

Next, we set the verify property of options to rawBodySaver and then use options as the argument for bodyParser.json to set rawBodySaver as the function to run when the request body is being parsed.

Then in the POST / route, we can get the raw request body from the req.rawBody property.

Categories
Express JavaScript Answers

How to Accept File Uploads with Express?

To accept file uploads in our Express apps, we can use the multer Express middleware.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000
const multer = require('multer');
const upload = multer({ dest: 'uploads/' })

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

app.post('/', upload.single('file'), (req, res) => {
  console.dir(req.file);
  res.send('uploaded')
});

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

to add the multer Express middleware.

To install it, we run:

npm i multer

Then to make the POST / route accept a file upload.

We call upload.single with the key of the form to get the file.

Then we can get the uploaded file with the req.file property.

The file will be stored in the /uploads folder as set as the value of the dest property.

Then if we make a request to the POST / route with a form data object that has the file key set to a file, the file will be uploaded.

Categories
Express JavaScript Answers

How to Call the Express res.sendFile Method with an Absolute Path?

To call the Express res.sendFile method with an absolute path, we can call the sendFile method with the root option set to the __dirname .

__dirname has the path string of the current working directory as its value.

For instance, we can write:

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

app.get('/', (req, res) => {
  res.sendFile('public/index.html' , { root : __dirname});
});

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

We call res.sendFile with the file path as the first argument.

It’s the path relative to the folder path set as the value of root .

root is set to __dirname , so the path in the first argument is relative to __dirname .

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.