Reputation: 1899
I'm currently testing out the endpoints on my server via a React client using Axios. I have a proxy (http://localhost:8080
) set up in my package.JSON for my client. All my GET requests are successful. My POST requests on the other-hand all fail to make use of the proxy provided in package.JSON, instead, it's using (http://localhost:3000
).
Please see code below
Login Component
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>
);
}
This is the solution I tried after my original attempt failed
Previous 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)
}
}
This solution also seems to direct requests to 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"
]
}
}
Any ideas as to how I can remedy this? Thanks for any and all suggestions.
Upvotes: 3
Views: 4181
Reputation: 943590
XMLHttpRequest doesn't provide an API to set a proxy server, so the config option isn't used with the xhr adaptor. It is only supported by the http adaptor which is used when you run Axios under Node.js.
If you want to use a traditional proxy server, you need to manually change the configuration of the browser (or the OS if the browser picks it up from there).
Upvotes: 2