Search code examples
node.jsreactjsproxyaxiosfetch

How can i use proxy url defined in package.json as axios proxy?


I was wondering, if i could avoid defining the backend's url in every single React file, where i use axios for requests?

I would use the proxy property defined in package.json somehow, and only adds the relative path on the current backend to send the query to the correct url.

If i'm right, in Fetch(), the proxy is the default, and only the path is required, can i reach the same with axios?

+--------------------------------------------------------+

Some examples

package.json:

[...]<br />
"proxy": "http://localhost/5000",<br />
[...]

React component:

[...]<br />
Axios.post("http://localhost:5000/login", { user: enteredUser, pw: enteredPw })<br />
                .then((res) => { console.log(res); } );<br />
[...]

I would like to change this, to:

[...]<br />
Axios.post("/login", { user: enteredUser, pw: enteredPw })<br />
                .then((res) => { console.log(res); } );<br />
[...]

Solution

  • Meanwhile, i've found the answer.

    In the React's index.js file I imported the axios, then with the Axios.defaults.baseURL function I defined the backend's URL, so now axios.post("/path"[...] is enough.

    P.S.: But the CORS is required to be okay.