I am developing a react project with backend in python. In production build for POST API getting CORS error and after that in network section getting preflight and in request method getting OPTIONS as a value at place of POST. Same POST api I’m calling above without payload it is working fine but with payload it is giving CORS error. GET API at the same IP is working but POST is not working. I am not able to figure out why POST is not working.
CODE:
import React, { useState, useEffect, useRef, useMemo } from "react";
import Button from "@mui/material/Button";
import "../../src/input.css";
import "bootstrap/dist/css/bootstrap.css";
import { AgGridReact } from "ag-grid-react";
import "@ag-grid-community/all-modules/dist/styles/ag-grid.css";
import "@ag-grid-community/all-modules/dist/styles/ag-theme-alpine.css";
import "ag-grid-enterprise";
import { toast } from "react-toastify";
import IosShareIcon from "@mui/icons-material/IosShare";
import XLSX from "xlsx";
import { read, utils } from "xlsx";
// import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import axios from "axios";
import MockLoaderTable from "./MockLoader";
import DateCellRenderer from "./DateCellRenderer";
import "../App.css";
import { useNavigate, useParams, useLocation } from "react-router-dom";
import configDevelopment from "../config.development";
import configProduction from "../config.production";
function Table() {
const gridApiRef = useRef(null);
// const [gridApi, setGridApi] = useState(null);
const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
const ITEMS_PER_PAGE = 10; // Adjust as needed
const gridRef = useRef(); // Temporary state to hold changes
const [data, setdata] = useState([
{
"@odata.etag": 'W/"JzE5OzUzMDQ1NDYwMzAzNDIzMzY2NDIxOzAwOyc="',
SystemId: "a999ee0f-2301-ee11-8f6e-000d3af2c8b8",
DocumentNo: "SOCBFOC23240001",
DocumentType: "Order",
LineNo: 10000,
Type: "G/L Account",
No: "44-022110",
PartNo: "",
Description: "Mounting of AP's",
RequestedDeliveryDate: "2024-12-28",
OrderStatus: "Open",
},
]);
const [loading, setLoading] = useState(false); // State for loading indicator
const [postloader, setpostloader] = useState(false);
const [isSubmitDisabled, setIsSubmitDisabled] = useState(true);
// const { documentNo } = useParams();
const navigate = useNavigate();
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const documentNo = queryParams.get("DocumentNo");
const apiUrl = configProduction.apiUrl;
const [message, setMessage] = useState("");
const exportParams = {
skipHeader: false,
skipFooters: true,
skipGroups: true,
fileName: "data.csv",
};
const handleDateChange = (rowIndex, date, changed) => {
setdata((prevData) => {
const newData = [...prevData];
if (newData[rowIndex]) {
newData[rowIndex].RequestedDeliveryDate = date.format("YYYY-MM-DD");
newData[rowIndex].dateChanged = changed;
setIsSubmitDisabled(false); // Enable the Submit button when any date is changed
}
return newData;
});
};
const frameworkComponents = {
dateCellRenderer: (props) => {
return <DateCellRenderer {...props} onDateChange={handleDateChange} />;
},
};
const getAllData = (documentNo) => {
setLoading(true);
axios
.get(`http://192.168.11.3:8001/v1/api/bcdata?DocumentNo=${documentNo}`)
.then((response) => {
setdata(response.data.data);
setLoading(false);
// Update URL without triggering a full page reload
const newUrl = `${window.location.origin}${window.location.pathname}?DocumentNo=${documentNo}`;
window.history.pushState({ path: newUrl }, "", newUrl);
})
.catch((error) => {
console.error("No data present");
setLoading(false);
});
};
useEffect(() => {
getAllData(documentNo);
}, [documentNo]);
useEffect(() => {
axios
.post(`http://192.168.11.3:8001/v1/api/bcdata`)
.then((response) => {
setMessage(response.data.message);
})
.catch((error) => {
console.log(error);
});
}, []);
const handleSubmit = () => {
const formattedData = data.filter((item) => item.dateChanged === true);
const selectedKeys = [
"@odata.etag",
"SystemId",
"RequestedDeliveryDate",
"OrderStatus",
];
const extractedData = formattedData.map((item) => {
const selectedData = {};
selectedKeys.forEach((key) => {
selectedData[key] = item[key];
});
return selectedData;
});
const modifiedArray = extractedData.map((item) => {
const { "@odata.etag": _, ...rest } = item; // Extract the key and ignore it
return { odata: item["@odata.etag"], ...rest };
});
console.log(modifiedArray);
setpostloader(true);
axios
.post(
"http://192.168.11.3:8001/v1/api/bcdata?DocumentNo=${documentNo}",
modifiedArray,
{
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers": "*",
},
}
)
.then((res) => {
console.log("post resp", res);
getAllData(documentNo);
setIsSubmitDisabled(true);
toast.success("Successfully changed the date, LOADING THE DATA!!!");
setpostloader(false);
})
.catch((err) => {
toast.error("Something went wrong");
setpostloader(false);
});
};
const headers = [
{
headerName: "Document Number",
field: "DocumentNo",
filter: true,
},
{
headerName: "Description",
field: "Description",
filter: true,
},
{
headerName: "Part Number",
field: "PartNo",
filter: true,
},
{
headerName: "Type",
field: "DocumentType",
filter: true,
},
{
headerName: "Line Number",
field: "LineNo",
filter: true,
},
{
headerName: "Order Status",
field: "OrderStatus",
filter: true,
},
{
headerName: "Requested Delivery Dates",
field: "RequestedDeliveryDate",
filter: true,
cellRendererFramework: (params) => (
<DateCellRenderer
{...params}
onDateChange={handleDateChange}
orderStatus={params.data.OrderStatus} // Make sure to pass the correct field here
/>
),
width: "400%",
},
];
return (
<div style={tablestyle.table}>
{loading || postloader ? (
<MockLoaderTable postloader={postloader} loading={loading} />
) : data.length > 0 ? (
<>
<div className="d-flex" style={{ justifyContent: "flex-end" }}>
<div>
<Button
style={tablestyle.btn}
variant="contained"
onClick={handleSubmit}
disabled={isSubmitDisabled}
>
Submit
</Button>
</div>
<div style={{ display: "flex", alignItems: "center" }}>
<div
style={{
cursor: "pointer",
marginRight: "-0.5rem",
}}
onClick={() => {
if (gridApiRef.current) {
gridApiRef.current.exportDataAsCsv(exportParams);
}
}}
>
<IosShareIcon style={{ color: "0093fb" }} />
</div>
<Button
style={{
color: "#0093fb",
display: "inline",
marginTop: "0.5rem",
}}
onClick={() => {
if (gridApiRef.current) {
gridApiRef.current.exportDataAsCsv(exportParams);
}
}}
>
Export to CSV
</Button>
</div>
<div>
{/* <input
style={{
color: "#0093fb",
display: "inline",
marginTop: "0.5rem",
}}
type="file"
onChange={handleFileChange}
/> */}
</div>
{/* Dropdown for column selection */}
</div>
<div style={containerStyle}>
<div className="ag-theme-alpine">
<AgGridReact
columnDefs={headers}
rowData={data}
domLayout="autoHeight"
suppressMenuHide={true}
pagination={true}
frameworkComponents={frameworkComponents}
paginationPageSize={ITEMS_PER_PAGE}
onGridReady={(params) => {
gridApiRef.current = params.api;
}}
/>
</div>
</div>
</>
) : (
<h2>No Data Found !!!</h2>
)}
</div>
);
}
export default Table;
const tablestyle = {
table: {
overflowX: "auto",
marginBottom: "3rem",
margin: "2rem",
},
btn: {
float: "right",
marginBottom: "0.5rem",
marginRight: "1rem",
},
heading: {
display: "flex",
justifyContent: "center",
},
};
I want solution to avoid CORS error in POST call.