我目前正在使用Axios通过React客户端在服务器上测试端点。我在package.JSON中为我的客户端设置了一个代理(http://localhost:8080
)。我所有的GET请求均成功。另一方面,我的POST请求都无法使用package.JSON中提供的代理,而是使用(http://localhost:3000
)。
请参阅下面的代码
登录组件
function Login{
const handleSubmit = (e) =>{
e.preventDefault();
let email = e.target.email.value;
let password = e.target.password.value;
axios.post("/user/login", {email:email, password:password})
.then((res) => console.log(res))
.catch((err) => console.log(err));
}
return(
<div className="form login">
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<input type="email" placeholder="Email" name="email"/>
<input type="password" placeholder="Password" name="password"/>
<input type="submit"/>
</form>
</div>
);
}
这是我最初尝试失败后尝试的解决方案
上一个handleSubmit()
const handleSubmit = (e) =>{
try{
let res = await axios({
method: "post",
url: "/user/login",
data: {},
proxy:{
host: "localhost",
port: "8080"
}
})
console.log(res);
}
catch(err){
console.log(err)
}
}
此解决方案似乎也将请求定向到http://localhost:3000
Package.JSON
{
"name": "client",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:8080",
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.4.0",
"@testing-library/user-event": "^7.2.1",
"axios": "^0.19.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-router-dom": "^5.1.2",
"react-scripts": "3.3.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
关于如何解决此问题的任何想法?感谢您提出的所有建议。
XMLHttpRequest不提供用于设置代理服务器的API,因此xhr adaptor不使用config选项。仅在Node.js下运行Axios时使用的http adaptor支持它。
[如果要使用传统的代理服务器,则需要手动更改浏览器(或OS,如果浏览器从那里进行安装,则为OS)。