Categories
Express JavaScript Answers

How to Accept form-data Request Data with Express?

To accept form-data request data in our Express app, we can use the body-parser package.

To install it, we run:

npm i body-parser

Then we can use it by writing:

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

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({ extended: true }));

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

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

so that we can accept form-data requests in our Express app.

We call bodyParser.urlencoded to accept form-data requests.

The extended option lets us choose between parsing the URL-encoded data with the querystring library with its set to false or the qs library when it’s set to true .

Therefore, when we make a x-www-form-urlencoded request with some key-value pairs, we should get them in the req.body object.

So we’ll see them returned as the response when we make a POST request to the / route.

Categories
Express JavaScript Answers

How to Add a Single Routing Handler for Multiple Routes in a Single Line with Express?

To add a single routing handler for multiple routes in a single line with Express, we can pass in an array of route path patterns that will be handled by one route handler.

For instance, we can write:

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

const routes = ['/', '/foo', '/bar', '/baz/:id']
app.get(routes, (req, res) => {
  res.send('hello world')
});

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

We have the routes array that has strings with different route path patterns.

And we use it as the first argument of the app.get method.

Therefore, when we go to / , /foo , /bar or /baz with anything after it, we’ll see hello world displayed.

This also works with app.post , app.delete , app.put , and other route defining methods.

Categories
Express JavaScript Answers

How to Accept Multiple URL Parameters in Express Routes?

To accept multiple URL parameters in Express routes, we can put them as the placeholders for each URL parameter in the route path string.

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('/fruit/:fruitName/:fruitColor', (req, res) => {
  const {
    fruitName,
    fruitColor
  } = req.params
  res.json({
    fruitName,
    fruitColor
  });
});

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

We add the ‘/fruit/:fruitName/:fruitColor’ route, where :fruitName and :fruitColor are the URL params placeholders.

We can get the values of them from the req.params object.

Then, we return the extracted parameter values in the response object with res.json .

So if we make a GET request to /fruit/apple/green , we see:

{
    "fruitName": "apple",
    "fruitColor": "green"
}

returned as the response.

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.