'React not using proxy url to post the data to the server
For the front end, I have a code in react js and I am trying to post the JSON data as a query from react to express.
Express server is running on port 5000
const [ search, setSearch ] = useState("");
const updatesearches = async () => {
const result = await fetch("/api/searchposts",{
method: "POST",
body: JSON.stringify({search}),
headers: {
"Content-Type" : "application/json",
}
});
const res = await result.json();
console.log(res);
}
useEffect(() => {
updatesearches();
},[search])
The server is working perfectly which I already have tested on the postman. For the back end here is the code of the exrpess controller:
const { PostModel } = require("../models");
const getsearchposts = async (req , res) => {
const result = await PostModel.find({title : "Ukraine war: Gruesome evidence points to war crimes on road outside Kyiv"});
res.send(result);
}
module.exports = { getsearchposts };
In the postrouters.js file
const express = require("express");
const router = express.Router();
const { getsearchposts } = require("../controllers/getsearchposts");
router.post("/api/searchposts", getsearchposts );
module.exports = router;
And in the react package.json file i have used "proxy" : "http://localhost:5000",
The output is printed on the browser console when i change the search state is below
POST http://localhost:3000/api/searchposts net::ERR_INTERNET_DISCONNECTED
Sidebar.js:9 Uncaught (in promise) TypeError: Failed to fetch
at updatesearches (Sidebar.js:9:1)
at Sidebar.js:22:1
at invokePassiveEffectCreate (react-dom.development.js:23479:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at flushPassiveEffectsImpl (react-dom.development.js:23566:1)
at unstable_runWithPriority (scheduler.development.js:468:1)
at runWithPriority$1 (react-dom.development.js:11268:1)
at flushPassiveEffects (react-dom.development.js:23439:1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
