Categories
Express JavaScript Answers

How to Return JSON Responses with Express?

To return JSON responses with Express, we can use the res.json method to return a JSON response.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000
app.set('json spaces', 2);

app.get('/', (req, res) => {
  const obj = { foo: 1, bar: 2, baz: 3 }
  res.json(obj)
})

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

We call app.set to set the 'json spaces' setting to 2 to make the indentation of the JSON 2 spaces.

Then in the GET / route, we call res.json with an object to return the obj object as the response.

Therefore, the response we get is:

{
  "foo": 1,
  "bar": 2,
  "baz": 3
}

when we go to the GET / route.

Categories
Express JavaScript Answers

How to Fix the ‘Error: request entity too large’ in Express and JavaScript?

To fix the ‘Error: request entity too large’ in Express, we can set the limit option when we add body-parser into our Express app.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser')
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));

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

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

to set the max size of JSON and URL encoded request data to 50MB by setting limit to '50mb' .

Categories
Express JavaScript Answers

How to Access POST Form Field Values with Express?

To access POST form fields values with Express, we can use the body-parser middleware to parse the POST form fields into a JavaScript object.

To install the package, we run:

npm install --save body-parser

Then we can write:

const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

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

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

to add body-parser into our app with:

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

Now we can parse JSON or URL encoded request data into the req.body property.

Therefore, when we send request data into the POST / route, we see the request value returned as the response in an object.

Categories
Express JavaScript Answers

How to Get Query String Variables in Express.js on Node.js?

To get query string variables in Express.js on Node.js, we can use the req.query property.

For instance, we can write:

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

app.get('/', (req, res) => {
  res.json(req.query)
})

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

to return the req.query object as the response in the / route.

Then when we add ?foo=bar at the of the URL as the query string, we should see:

{
  "foo": "bar"
}

returned as the response.

Categories
Express

How to Let Users Download a File from Node.js Server with Express?

Sometimes, we want to let users download files within our Express app.

In this article, we’ll look at how to let users download files from Express apps.

res.download

One way to let users download a file from a Node.js server is to use the res.download method available with Express.

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('/download', (req, res) => {
  const file = `${__dirname}/download/foo.txt`;
  res.download(file);
});

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

We just specify the path to the file with the file string variable.

Then we pass that to the res.download method to download the file.

__dirname is the current working directory of the Express app.

Serve Files as Static Files

We can also use the express.static middleware to serve a folder in our server as a static files folder.

To do this, we write:

const express = require('express')
const app = express()
const port = 3000
app.use('/download', express.static('download'))

app.get('/', (req, res) => {
  res.send('Hello World!')
})

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

We call app.use to use the Express static middleware.

The first argument is the path that the user uses to access the static folder’s content.

And the 2nd argument is the Express static middleware.

We create the middleware by calling express.static with the folder path string.

Therefore, we serve the download folder in our server as the static folder.

res.attachment

We can also return a file as a response in our route with the route.attachment method.

It takes the same argument as the res.download method.

It sets the Content-Disposition response header to attachment .

And it also sets the Content-Type response header according to the file type being downloaded.

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('/download', (req, res) => {
  const file = `${__dirname}/download/foo.txt`;
  res.attachment(file).send();
});

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

We call res.attachment with send to send the file download response to the user.

Conclusion

There’re several ways we can use to let users download files to user’s device via an Express endpoint.