I have a React.js task that requires me to make a POST request to the server. Now, I want to send a POST request when a user clicks a submit button. But I keep getting these 2 errors:
App.js:19 POST http://localhost:3001/ net::ERR_CONNECTION_RESET
App.js:19 Uncaught (in promise) TypeError: Failed to fetch at handleSubmit (App.js:19:1)
My React code:
import "./App.css";
function App() {
const [inputs, setInputs] = useState({});
const [backendData, setBackendData] = useState();
const handleChange = (e) => {
const name = e.target.name;
const value = e.target.value;
setInputs((state) => ({ ...state, [name]: value }));
};
const handleSubmit = (e) => {
e.preventDefault();
/*when submit is clicked, we are goint to send a POST request so that data of the inputs is created*/
console.log(inputs);
fetch("http://localhost:3001/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(inputs),
});
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input
type="text"
name="projectTitle"
onChange={handleChange}
className="project-title"
value={inputs.projectTitle || " "}
/>
<input
type="text"
name="id"
className="id"
onChange={handleChange}
value={inputs.id || " "}
/>
<input type="submit" value="Submit" />
</form>
</div>
);
}
export default App;
My Express code:
const express = require("express");
const app = express();
const fs = require("fs");
const cors = require("cors");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
var obj = { projects: [] };
app.post("/", (req, res, next) => {
let identifier = req.query.identify; //id of project
fs.readFile("webProjects.json", (err, data) => {
if (err) throw err;
obj = JSON.parse(data);
obj.projects.push({
id: identifier,
title: req.query.project,
description: req.query.description,
});
let json = JSON.stringify(obj);
fs.writeFile("webProjects.json", json, (err) => {
if (err) throw err;
console.log("updatedd", req.body.inputs);
});
});
});
/*when user sends delete request, delete specific data.*/
app.delete("/", (req, res, next) => {
fs.readFile("webProjects.json", (err, data) => {
console.log(data);
obj = JSON.parse(data);
// assign the filtered array back to the original array
obj.projects = obj.projects.filter((item) => {
let url = req.query.identify;
return item.id !== url;
});
console.log(obj);
let json = JSON.stringify(obj);
fs.writeFile("webProjects.json", json, (err) => {
if (err) throw err;
console.log(obj);
});
});
});
/*when user navigates to another page, we display the data of the resource*/
app.get("/api", (req, res, next) => {
fs.readFile("webProjects.json", (err, data) => {
if (err) throw err;
res.json(JSON.parse(data));
console.log("done");
});
});
/*we want to catch all errors, with the requests made to the server.
used the wildcard(*) to make sure that we catch all requests made to the server.
*/
app.get("*", (req, res, next) => {
let err = new Error("There was an error in accessing the page you wanted");
err.statusCode = 404;
next(err);
});
app.use((err, req, res, next) => {
console.log(err.message);
if (!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).send(err.message);
});
let PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log("server has listened");
});
CodePudding user response:
If the front end is created with create-react-app
command, the problem might be the proxy one. In your package.json
file, you can add proxy as shown below:
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:3001"
CodePudding user response:
The first error net::ERR_CONNECTION_RESET
means that the browser is unable to make a connexion to the server. Here is how you could approach the issues you are having:
- Make your server is running, in your case make sur your Express app is running. For that you could check the console.
- Set up a proxy if you are using a tool like
create-react-app
who has a local development server.
If you are using
create-react-app
, there are two ways to setup a proxy. But for a proxy to work, you should have a url that's not handled in your Front End. For example you could make sure that all your API endpoints start with/api/
.
- Add this line
"proxy": "http://localhost:3001"
at the end of yourpackage.json
- If the above solution doesn't work, create a
setupProxy.js
in src folder, next toindex.js
and past in it:const { createProxyMiddleware } = require("http-proxy-middleware"); module.exports = function (app) { app.use( "/api", createProxyMiddleware({ target: "http://localhost:3001", changeOrigin: true, }) ); };
Open your terminal in your React root folder, and run:
npm i http-proxy-middleware && npm start