如何使用 package.json 中定义的代理 url 作为 axios 代理?

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

我想知道,如果我可以避免在每个 React 文件中定义后端的 url,我在哪里使用 axios 进行请求?

我会以某种方式使用 package.json 中定义的代理 属性,并且只在当前后端添加相对路径以将查询发送到正确的 url.

如果我没看错,在Fetch()中,代理是默认的,只需要路径,我可以用axios达到同样的效果吗?

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

一些例子

package.json:

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

React 组件:

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

我想将其更改为:

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

与此同时,我找到了答案。

在 React 的 index.js 文件中我导入了 axios,然后使用 Axios.defaults.baseURL 函数我定义了后端的 URL,所以现在 axios.post("/path" [...] 就够了。

P.S.: 但是要求CORS没问题