Categories
Express JavaScript Answers

How to Fix the ‘req.files undefined’ Error with Express?

To fix the ‘req.files undefined’ error in our Express app when we try to add file upload feature into our Express app, we should add a file upload handling library into our Express app.

For instance, we can use the express-fileupload library by installing it with:

npm i express-fileupload

Then we can use the library by writing:

const express = require('express')
const app = express()
const port = 3000
const fileupload = require("express-fileupload");
app.use(fileupload());

app.post("/", (req, res) => {
  if (!req.files) {
    res.send("File was not found");
    return;
  }

  const file = req.files.file;
  res.send(`${file.name} File Uploaded`);
});

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

we add the fileUpload middleware with:

const fileupload = require("express-fileupload");
app.use(fileupload());

Now the uploaded file can be accessible from the req.files object.

file is the key of the form data that has the file as its value.

And we can get the name of the file with the file.name property.

Categories
Express JavaScript Answers

How to Render a Basic HTML View in an Express App?

To render a basic HTML view in an Express app, we can install a templating library that works with Express.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');

app.get("/", (req, res) => {
  res.render('about.html');
});

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

to add the ejs library by installing:

npm i ejs

Then we write:

app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');

to serve the views folder to serve that has the template folder.

We specify that we use the ejs templating engine with the last 2 lines.

Then in the / route, we call res.render with 'about.html' to serve the content of that as the template.

In about.html , we have:

about

as its content.

And so when we go to / , we see about displayed.

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.