Felipe Augusto
Felipe Augusto

Reputation: 8184

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.

Upvotes: 9

Views: 13602

Answers (2)

Avijeet Gaikwad
Avijeet Gaikwad

Reputation: 59

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.

Upvotes: 5

Felipe Augusto
Felipe Augusto

Reputation: 8184

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.

Upvotes: 1

Related Questions