Reputation: 33
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
Reputation: 944005
You have three layers here. EJS is the least relevant one of these.
router.get
) which runs on the server and handles the business logic.<script>
elements) which run on the clientBut 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:
<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).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