profile-picture

Dominic Johnson

Software Developer

TwitterGithubLinkedinYouTube

Connecting Frontend With Backend Using API

January 10, 2019 (5y ago)

Frontend is all about beautifying the user experience, by adding colors, images or animations to the website. The backend is responsible for storing user data, handing business logic and making sure that users are able to access their information. Since both of these applications often speak their own language, it can be difficult for developers to connect them. This article talks about how you can connect frontend with backend app in an efficient way.

What Is an API?

API stands for Application Programming Interface, which is a set of instructions for making an application work. It makes it easy for developers to work with different languages. If we see website or app development from the view of an architect, we can say that frontend is the building and backend is the blueprint. The blueprint helps in designing the building. In the same way, API helps in designing the frontend.

Why Is It Important To Use APIs?

The user experience depends on the data that is being sent from the backend. If the data is not accurate, the user experience will be negatively affected. In order to get the accurate data you need to connect to a backend application. This is where APIs come into play. They help in connecting the frontend with the backend. APIs are also used to connect different applications. For example, if you want to connect your website with a third party application, you can use an API to do so.

The main objective of using APIs is to connect two different applications together. An API allows the two applications to talk to each other and exchange data without any human intervention. When a frontend application is connected to backend application via API, a user clicks on some data, the frontend will make a request to the backend application. The backend then handles some type of business logic, then fetches the data from the database and sends it back to the frontend application. The frontend application receives the data from backend API and displays the data to the user.

How To Connect The Frontend With The Backend ?

It's better to build than just read about it. Let's get our hands dirty!

Creating A Backend Using Node.js

First of all, you need to install node.js if you haven't already. Then you need to create a folder and open it in the command prompt. Once that is done run the following command to install express and CORS:

npm install express cors

Then you need to run the following command in the command prompt to create a new file called app.js:

touch app.js

Within app.js, you need to add the following code:

//app.js
const express = require('express');
const cors = require('cors');
const app = express();
const port = 8000;

app.use(cors());
app.use(express.json());

app.get('/', (req, res) => {
  res.json({
    id: 1,
    name: 'John Doe',
    description: 'This is a test description',
    price: 100,
  })
});

The above code will create a server on port 8000. Then you need to run the following command to start the server:

node app.js

Then you can go to the following URL in the browser to see the result:

http://localhost:8000

   

Creating A Frontend Using React.js

Create a new folder name it frontend and open it in the command prompt. Then run the following command to install react:

npx create-react-app .

Then you need to run the following command to install axios:

npm install axios

now create a new file called App.js and add the following code:

//App.js
import { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
  const [data, setData] = useState({});

  useEffect(() => {
    axios.get('http://localhost:8000')
      .then((response) => {
        setData(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.description}</p>
      <p>{data.price}</p>
    </div>
  );
}

export default App;

The above code will fetch data from the backend API and display it on the frontend.

Then start the server:

npm start

Then you can go to the following URL in the browser to see the result:

http://localhost:3000

🎉 Congratulations! You have successfully connected the frontend with the backend.

Conclusion

The article discussed how to connect the frontend with the backend via API. It also discussed why it is important to use APIs, as well as how to build an API using Node.js and React.js. I hope you found this article helpful. If you have any questions, feel free to reach out.

© 2024 Dominic Johnson