I've set up a working, very simple express server with ejs as my view engine.
My web page has a form, and with the press of an html button the input is turned into the json object userFormData. I have another node.js file that handles interactions with an API. On this file, I have a function createNewFromUserFormData(userFormData). I now wonder what the best way would be to get my userFormData from the front end, to the API handling js node on the back end. Is there any way I can call a function on the node from the frontend index.ejs in the view folder?
Basically my question is just: How can I export json from the webapp to a node server? Is there any way I can call a function on the backend from a onclick on the index.ejs?
EJS (Embedded JavaScript) is a template engine using vanilla JavaScript which will result in static HTML document (or partials).
Handling any events (Network, user...) would go into the HTML document embedded scripts.
You should be able to attach an event handler as the onclick function calling your backend API (with whatever content you should send along as request payload).
Below is an example of a simple EJS template file using vanilla JavaScript to register a click event handler which fetches a remote API (which should be your internal route endpoint) to display its result:
<span id='link'>
<% if (true) { %>
<%= 'Guess what to do?' %>
<% } %>
</span>
<p id="activity"></p>
<script>
const linkNode = document.querySelector('#link');
linkNode.addEventListener('click', () => {
fetch('https://www.boredapi.com/api/activity')
.then((res) => res.json())
.then((res) => {
const textNode = document.querySelector('#activity');
textNode.textContent = res.activity;
});
});
</script>