Categories
Express JavaScript Answers

How to Redirect in Express.js While Passing Some Data to the Destination?

To redirect in Express.js while passing some data to the destination, we can pass cookies from the originating route to the destination route.

For instance, we can write:

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

app.use(cookieParser());

app.get("/", (req, res) => {
  const context = req.cookies["context"];
  res.clearCookie("context", { httpOnly: true });
  res.send(context);
});

app.get("/category", (req, res) => {
  res.cookie("context", "foo", { httpOnly: true });
  res.redirect("/");
})

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

We have the /category route which sets the context cookie with the res.cookie method.

'context' is the key, 'foo' is the value. httpOnly sends the cookie via HTTP only.

We redirect with the res.redirect method.

The / route is the desination route.

We get the cookie with req.cookies with the 'context' key.

Then we call res.clearCookie with the 'context' key to clear that cookie.

And then we call res.send with context to return the cookie value as the response.

Therefore, when we go to the /category route, we should be redirected to the / route, which returns foo as the response.

Categories
Express JavaScript Answers

How to Serve Static Files with Express.js?

To serve static files with Express.js, we can use the express.static middleware.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000
app.use(express.static(__dirname + '/public'));

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

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

We call app.use with express.static(__dirname + ‘/public’) to serve the public folder in the project folder as the static folder.

This will expose the folder’s contents to the public.

Therefore, if we have a foo.txt file in the public folder, we can go to /foo.txt to see its contents.

Categories
Express JavaScript Answers

How to Fix the Express.js ‘req.body undefined’ Error with JavaScript?

To to fix the Express.js ‘req.body undefined’ error, 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 to ${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 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' .