Rest API in Node and Express, use with ejs and React.js

Viewed 1942

I have created REST API with Nodejs and express, which will be used by ReactJS or PHP in the frontend by other developers.

Now I also want to use that API in the same project with EJS. Is it possible to use the same APIs with EJS, If yes, then what is the correct way to call that APIs with EJS Template Engine?

2 Answers

There are multiple ways how you can use this. You can either fetch your data and pass the values to the view.

So for an example:

app.get('/', function (req, res) {
  const users = await db.users.find({});
  res.render('index', { users })
})

In this case index will be the ejs template where you can render the list of users.

Alternatively you can also use javascript with your template and call your APIs as an ajax call.

The best way to go about this would be to call your API from the router/controller and pass an object with local variables for the view.

Assuming you have a template that looks like the following:

<!-- views/posts.ejs -->
<div>
  <% items.forEach(function(item) { %>
    <ul>
      <li><%= item.userId %></li>
      <li><%= item.id %></li>
      <li><%= item.title %></li>
      <li><%= item.body %></li>
    </ul>
  <% }); %>
</div>

Then, inside your route handler, you will do the following:

const express = require("express");
const app = express();

app.route("/posts")
  .get(function (req, res) {
    axios
      .get("https://jsonplaceholder.typicode.com/posts")
      .then(function (result) {
        res.render("posts", {
          items: result.data
        });
      })
      .catch(function (error) {
        // handle errors appropriately
        res.render("error", { error });
      });
  });
Related