I have created my API for my hobby project. But I need to connect it to the front end which is a react app.
What are the ways to connect it. I am using express as server and mongo atlas as my db.
Hello. Front end communicates with back end with API calls. The backend has an open port, usually port 80 and it accepts calls that correspond to defined routes. Let's say that you have on backend:
/profile - gets you callers profile stats
/get_all - lists all users registered on the server
that means that you are waiting for someone to make those instructions and you are ready to serve them back. You can open, for example, Postman and send the request to your server:
www.server.com/profile
and your server will deliver back the stats as you have defined on your backend. Or:
www.server.com/get_all
will return you a JSON list, for example, of the users that have registered on the website.
It is recommended beyond a reasonable doubt that you use services like Postman to check the validity of the data that you are expecting to get from the server before you start implementing that with the front end.
Now, when those tests pass, you can go on your react app or whatever app and make, for example, simple xmlhttprequest:
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "www.server.com/profile");
oReq.send();
or you can use some fetch:
fetch('www.server.com/profile')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson)
});
or, you can use some libraries like AXIOS to achieve the same thing.
To conclude. Make a server that listens and responds to some string (/profile, /get_all), test with Postman, make one of the calls from the front end like I have made examples above.
Yashu Mittal
Full Stack Dev
Yashu Mittal
Full Stack Dev
What kind of APIs? Rest APIs.