I'm having some troubles trying to make my backend and front communicate to each others (reactjs + vanilla NODEjs), both on different localhost port (4000 and 3000)
I managed to make it work until i wanted to try to add data to my database. I can GET data with my react app but i can't POST any data. Here is the code for both sides :
front : `
const sendData = async (event: any): Promise<void> => {
console.log("hello");
event.preventDefault();
const response = await fetch(`${_DATA_URL_}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(employeeForm),
});
const data = await response.json();
console.log(data);
};
` back :
const Router = (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, Accept, Origin, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, PATCH, OPTIONS"
);
console.log("hello"); //debug
if (req.method === "GET") {
if (req.url === "/api/employees") {
getEmployees(req, res);
} else if (req.url.match(/\/api\/employees\/(\w{4}-?){3}/)) {
const requestID = req.url.split("/")[3];
getEmployee(req, res, requestID);
} else {
res.statusCode = 404;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ message: `Error : ${req.url} not found !` }));
}
}
if (req.method === "POST") {
if (req.url === "/api/employees") {
createEmployee(req, res);
} else {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ message: `Error : ${req.url} not found !` }));
}
}
if (req.method === "DELETE") {
if (req.url.match(/\/api\/employees\/(\w{4}-?){3}/)) {
const requestID = req.url.split("/")[3];
deleteEmployee(req, res, requestID);
} else {
res.statusCode = 404;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ message: `Error : ${req.url} not found !` }));
}
}
if (req.method === "PUT") {
if (req.url.match(/\/api\/employees\/(\w{4}-?){3}/)) {
const requestID = req.url.split("/")[3];
updateEmployee(req, res, requestID);
} else {
res.statusCode = 404;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ message: `Error : ${req.url} not found !` }));
}
}
};
i'm pretty sure it comes from react side because posting data works fine when i use POSTMAN, and after a while on localhost i receive this error in the console :
Maybe i'm using cors incorrectly, anyways thanks for your futures answers