In this article, we will learn how to proxy backend servers using ReactJS. Sometimes, when building a web application with React.js, you may need to request a backend server. However, if the backend server does not allow Cross-Origin Resource Sharing (CORS), you may encounter an error when requesting from the frontend application. In this case, you can use the proxy server to forward requests from the front-end application to the back-end server. This can be done in React using a package called “HTTP-proxy-middleware”.
Prerequisite: To follow this guide, you will need to have Node.js and npm (Node Package Manager) installed on your computer.
Create ReactJS Application and Importing Required Module:
Step 1: Create a new React.js application using the following command
npx create-react-app my-app
Step 2: Install the “HTTP-proxy-middleware” package using the following command
npm install http-proxy-middleware --save
Step 3: Create a new file named “setupProxy.js” in the “src” directory of the React.js application. This information will be used to configure the name server.
Step 4: Add the following code to the “setupProxy.js” file
const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function (app) { app.use( '/api', createProxyMiddleware({ target: 'http://localhost:5000', changeOrigin: true, }) ); };
In this code, we set the proxy server to send requests to the “/api” path to the backend server running at http://localhost:5000. The “changeOrigin” option set to true allows the backend server to receive requests with the original host header.
Step 5: Update your React.js app to use the server name. For example, if you want to use the “fetch” API to make a request to the backend server, you can use the following code
fetch('/api/data') .then(response => response.json()) .then(data => console.log(data));
In this code, we request the path “/api/data” which will be sent from the proxy server to the backend server. The response from the backend server is then converted to JSON and saved to the console.
Project Structure:
Example: Here’s an example of how to use the proxy server in a React.js application.
Javascript
import React, { useEffect, useState } from 'react' ; function App() { const [data, setData] = useState( null ); useEffect(() => { fetch( '/api/data' ) .then(response => response.json()) .then(data => setData(data)); }, []); return ( <div> {data ? ( <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ) : ( <p>Loading...</p> )} </div> ); } export default App; |
In this code, we use the hooks “useState” and “useEffect” to make a request to the backend server and update the content of the state with the response. Then we present the information in the list. When the component is loaded for the first time, the “Loading… ” message will appear until the data is returned from the backend server.
Reference: https://create-react-app.dev/docs/proxying-api-requests-in-development/