govs
govs

Reputation: 135

How to set proxy for axios or fetch in Client side React

How to set porxy using for axios or fetch in Client side React(javascript).

Tried a lot of solutions but all fail to load the api. Tired axios-proxy-fix as well.

For a confirmation - The api works with Chrome CORS and Switchy proxy extention.

No Webpack-

Given ip and host e.g. x.x.x.x:xx

{
  "name": "testapp",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://X.X.X.X:X",
  "devDependencies": {
    "bootstrap": "^4.0.0-alpha.6",
    "jest": "^19.0.2",
    "material-ui": "^0.17.4",
    "node-sass": "^4.5.0",
    "nodemon": "^1.11.0",
    "npm-run-all": "^v4.0.1",
    "pushstate-server": "^3.0.0",
    "react-cookie": "^1.0.5",
    "react-scripts": "0.9.0",
    "redux": "^3.6.0",
    "jquery": "^3.1.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "axios-proxy-fix": "^0.16.3",
    "es6-promise": "^4.1.0",
    "isomorphic-fetch": "^2.2.1",
    "react-addons-css-transition-group": "^15.4.2",
    "react-addons-transition-group": "^15.4.2",
    "reactstrap": "^4.2.0",
    "tracer": "^0.8.7",
    "treeview-react-bootstrap": "^0.4.6",
    "tunnel": "0.0.6"
  },
  "scripts": {
    "build-css": "node-sass src/ -o src/",
    "watch-css": "nodemon -e scss -x \"npm run build-css\"",
    "start-js": "react-scripts start",
    "start": "npm-run-all -p watch-css start-js",
    "build": "npm run build-css && react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

And Component

  import axios from 'axios-proxy-fix';
    //OR 
    import axios from 'axios';

/*********
The not writing rest of component stuff only axios part 
***********/
    axios({
      method: 'get',
      url: '/api/some-endpoint',
      baseURL: "the-base-url",
      headers: {
        'httpAgent': 'new http.Agent({ keepAlive: true })',
        'X-Requested-With': 'XMLHttpRequest',        
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Content-Type': 'application/json;charset=UTF-8',
        "Access-Control-Allow-Origin": "*",
        "Proxy-Connection": "keep-alive"
      },
      proxy: {
        host: 'X.X.X.X',
        port: '80'
      }      
    })
      .then(res => {
        alert("ajax-respo-world");
        const posts = res.data.data;
        this.setState({ posts });
      }).catch(err => console.log("ajax-err", err))
   }

Upvotes: 0

Views: 3601

Answers (1)

govs
govs

Reputation: 135

I believe the conversation above is pretty much clear to conclude the answer that making an api call with a proxy is possible from server not from client.

Upvotes: 1

Related Questions