I have a ReactJS 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)
Link to React code:
import './App.css';
//Frontend
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;
Link to Server(express code)
/*Now, here we create a Restful api to allow a user to store a list[array] of web project items.*/
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")
})