Reputation: 89
I am getting this exact error when trying to send a POST request to log in a user:
[HPM] Error occurred while trying to proxy request /api/login from localhost:3000 to http://localhost:5000 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
At first i thought this was an issue relating to how the proxy was set up between the client and the server but I can fetch data from the backend perfectly fine. So the problem has to do when I am trying to post data to the backend (I think??)
Here is my React Login component:
import React from 'react'
class Login extends React.Component {
state = {}
handlChange = event => {
const { name, value } = event.target
this.setState({ [name]: value })
}
handleSubmit = () => {
fetch("/api/login", {
method: "POST",
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(this.state)
})
}
render() {
console.log(this.state)
return (
<div>
<form onSubmit={this.handleSubmit}>
<input type="text" name="username" value={this.state.username} onChange={this.handlChange} placeholder="Username" />
<input type="password" name="password" value={this.state.password} onChange={this.handlChange} placeholder="Password" />
<button>Login</button>
</form>
</div>
)
}
}
export default Login
I am using a setUpProxy.js file within the src folder as suggested by the React docs to set up the proxy, it looks like this:
const proxy = require("http-proxy-middleware")
module.exports = function(app) {
app.use(
'/api',
proxy({
target: 'http://localhost:5000',
changeOrigin: true
})
);
};
The client side app was built with create-react-app if that makes any difference
Upvotes: 2
Views: 4427
Reputation: 21
If you are using middleware from express like
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
You could try moving that middleware setup BELOW your proxy set up. From what I understand, the middleware for express that does the built in body parser functionality turns the request stream into a regular object, which may be the problem.
Moving the middleware below the proxy fixed our issue.
I know this post is pretty old but it seems to be the same as Github issue (Hanging Post requests).
That may or may not be the solution you need but maybe it will help someone out there...
Upvotes: 2
Reputation: 24565
We were facing a similar issue and as it turns out not all headers were forwarded by HPM. Try adding the Keep-Alive Header in the options:
const proxy = require("http-proxy-middleware")
module.exports = function(app) {
app.use(
'/api',
proxy({
target: 'http://localhost:5000',
headers: {
"Connection": "keep-alive"
},
followRedirects: true,
changeOrigin: true
})
);
};
Upvotes: 0