Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with two different APIs with React?

I need to test one endpoint inside an API, but I already work with one API, and I wouldn't like to change all my calls targeting just the new API.

I don't know event if it's possible, but is there some way to define more than one proxy inside package.json?

Is there some way to pass auth keys inside package.json?

The main server, is a local server, with a proxy:

"proxy": {
    "/api": {
      "target": "http://localhost:3001/proxy",
      "changeOrigin": true,
      "pathRewrite": {
        "^/api": ""
      }
    }
  },

Currently I'm using axios to make API calls, and the project was started with create-react-app.

like image 780
Felipe Augusto Avatar asked Jun 06 '18 17:06

Felipe Augusto


2 Answers

In package.json, you can configure the proxy server to make API requests to different targets based on maching the pattern for different API requests in the way it is shown as follows.

Things to note:

  • Order of the API patterns matters, the generic request(*) must be last.
  • The regex should be such that it matches the complete url, a partial match resulted in errors for me.

The following piece of code worked for me. There are 3 different servers, one for the reports request, one for the access control request, and rest all requests should go to the third server.

"proxy": {
    "/report/.*(_get)": {
      "target": "http://localhost:8093/"
    },
    "/access/.*(_get)": {
      "target": "http://localhost:8091/"
    },
    "/.*": {
      "target": "https://egov-micro-dev.egovernments.org/",
      "changeOrigin": true
    }
  },

Hope this helps.

like image 187
Avijeet Gaikwad Avatar answered Oct 25 '22 12:10

Avijeet Gaikwad


I found the solution adding the second proxy after the first one, inside the proxy and it was not necessary for me too put headers inside package.json, but the links shared by @Chase DeAnda are really interesting, and can help who is interested: Webpack headers and axios interceptors.

like image 39
Felipe Augusto Avatar answered Oct 25 '22 12:10

Felipe Augusto