Create an API and integrate it with the frontend
In this tutorial, we will guide you through the process of creating a backend file and seamlessly integrating it with a frontend file using MagicJS.
Creating Frontend and Backend Files
Let's start by creating a frontend file in the 'main-features' folder.
Add a new file by right clicking on 'main-features' folder.
Select 'Blank UI/React Component' and create a file named '
test-ui
'Give the path as '
/test-ui
' in the properties tab.Create a backend file using the 'Blank Backend Function' option and name the backend file as '
test
'.
Note that the 'server.tsx' extension will be automatically appended to the file by mern.ai.
It's important to append the 'server.tsx' extension manually for all backend functions when using other IDEs like VS Code.
In the backend file, you'll find a boilerplate for creating a backend function as given below:
This code defines a backend function using the
@magicjs.dev/backend
library, which, when invoked, will return the message "Message from server".
Calling Backend Function from Frontend
Let's trigger the backend function on a button click.
Refer the below code and update the
test-ui.tsx
file
In the above code, the button triggers a request to the backend server, and upon receiving a response, it displays the response message on the UI.
After saving the changes, test the functionality by clicking the button. You should see the message from the backend displayed on the frontend.
Our backend relies on Express.js for development.
🎉 Congratulations! You've learned how to create a backend function and seamlessly integrate it into the frontend using MagicJS framework.
Tired of Doing It All Yourself?
Get help from the experts behind MERN.AI IDE.
Our Professional Services team specializes in turning your ideas into fully functional applications. Focus on what you do the best and let us handle the development.
Last updated