Categories
Express JavaScript Answers

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

Sometimes, we want to add a single routing handler for multiple routes in a single line with JavaScript Express.

In this article, we’ll look at how to add a single routing handler for multiple routes in a single line with JavaScript Express.

Add a Single Routing Handler for Multiple Routes in a Single Line with JavaScript 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.

Conclusion

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.

Categories
Express JavaScript Answers

How to Accept Multiple URL Parameters in JavaScript Express Routes?

Sometimes, we want to accept multiple URL parameters in JavaScript Express routes.

In this article, we’ll look at how to accept multiple URL parameters in JavaScript Express routes.

Accept Multiple URL Parameters in JavaScript Express Routes

To accept multiple URL parameters in JavaScript 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 Render a Basic HTML View in a JavaScript Express App?

Sometimes, we want to render a basic HTML view in a JavaScript Express app.

In this article, we’ll look at how to render a basic HTML view in a JavaScript Express app.

Render a Basic HTML View in a JavaScript Express App

To render a basic HTML view in a JavaScript 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.

Conclusion

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

Categories
Express JavaScript Answers

How to Get All Registered Routes in Express and JavaScript?

Sometimes, we want to get all registered routes in Express and JavaScript.

In this article, we’ll look at how to get all registered routes in Express and JavaScript.

Get All Registered Routes in Express and JavaScript

To get all registered routes in Express and JavaScript, we can use the app._route.stack property.

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("foo", (req, res) => {
  res.send('foo')
});

app.get("bar", (req, res) => {
  res.send('bar')
});

app._router.stack.forEach((r) => {
  console.log(r.route && r.route.path)
})

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

to log all the registered routes with:

app._router.stack.forEach((r) => {
  console.log(r.route && r.route.path)
})

We get the pathname string with r.route.path .

Conclusion

To get all registered routes in Express and JavaScript, we can use the app._route.stack property.

Categories
Express JavaScript Answers Nodejs

How to render an error message when page is not found with Node.js and Express?

Sometimes, we want to render an error message when page is not found with Node.js and Express.

In this article, we’ll look at how to render an error message when page is not found with Node.js and Express.

How to render an error message when page is not found with Node.js and Express?

To render an error message when page is not found with Node.js and Express, we can add a middleware after all the route middlewares are added.

For instance, we write:

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

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

app.use((req, res, next) => {
  res.send('not found', 404);
});

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

We add a route with:

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

Then we add:

app.use((req, res, next) => {
  res.send('not found', 404);
});

which returns a 404 error for routes other than /.

We call app.use to add any middleware that are used app-wide.

Conclusion

To render an error message when page is not found with Node.js and Express, we can add a middleware after all the route middlewares are added.