I'm trying to use an express server with a react.js app and I faced an error in proxying. this is the error: [HPM] Error occurred while proxying request localhost:3000/api to http://localhost:3001/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors)
proxysetup.js:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:3001/',
changeOrigin: true,
})
);
};
App.js:
import React from "react";
import "./App.css";
function App() {
const [data, setData] = React.useState(null);
React.useEffect(() => {
fetch("/api")
.then((res) => res.json())
.then((data) => setData(data.message));
}, []);
return (
<div className="App">
<header className="App-header">
<p>{!data ? "Loading..." : data}</p>
</header>
</div>
);
}
export default App;
server.js:
const express = require("express");
const PORT = process.env.PORT || 3001;
const app = express();
app.get("/api", (req, res) => {
res.json({ message: "Hello from express!" });
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});