Jin
Jin

Reputation: 33

is there any way to call axios from ejs?

I just coded sample files.

my ejs file display some data after receiving the data from API call.

my code is shown as below and the pattern of my code follows

node(router) --> call api(axios) --> display data on the ejs file.

//index.js

...
...
router.get('/dashboard', function(req,res,next){
  try {
    let result = await axios({ //Call API
      method: 'get',
      url: 'http://localhost:3001/user',
      data: {
        id: '1129',
        lastName: 'Test'
      }
    }); 
  

      res.render('dashboard', {data: result.data}); //display the received data
    } catch (error) {
      next(error)
  }
})
module.exports = router;
//dashboard.ejs

...
...
<div>
   <p>js data : <%=data%></p> //displays the data I jsut received from Axios
</div>

...
...

But what if some client types input value and I want to execute API call(post or put) with the client input value?

likes.. get client value from ejs --> send the value to node(router) --> call api(axios)

is there any way to do that?(without ajax, because I am trying not to use ajax).

Upvotes: 0

Views: 1674

Answers (1)

Quentin
Quentin

Reputation: 944005

You have three layers here. EJS is the least relevant one of these.

  • The controller (the function you pass to router.get) which runs on the server and handles the business logic.
  • The view (the EJS template) which runs on the server and handles the display logic (converting the data into HTML).
  • Client-side JS (<script> elements) which run on the client

But what if some client types input value and I want to execute API call(post or put) with the client input value?

Then you have two options:

  • Submit a <form> to a URL that is handled by a controller (which then uses axios server side, gets some data, populates an EJS view and returns a new page to the client).
  • Read the data with client-side JS, use Ajax to send it to a URL (which could be a URL you provide which is handled by a controller), have that controller return data (which could be HTML generated by EJS or plain JSON) and then use client-side JS to insert it into the page.

If you don't want to use Ajax, then you have to use a form submission and load a new page.


While it might be possible to call Axios from EJS (I have a feeling the asynchronous nature of it would break things) that is effectively the same as the form submission option, but it puts business logic in the view layer, which is confusing at best.


Related: What is the difference between client-side and server-side programming?

Upvotes: 1

Related Questions