I'm trying to fetch data from an API using reactJS, I used postman to test the API and it returns a JSON, but when I try from my reactJS application the web browser returns this error.
"Access to fetch at 'http://XX.XX.XX.XX*/v1/shipping' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
Does anyone know why it's not working in the browser, but it works on postman?
Here is the fetch function.
fetchingData = () => {
const bodyReq = {
"bu":"",
"customer":"",
"start_time":"",
"end_time":"",
"serial_number":"XXXXXXXXXXXXX,XXXXXXXXXXXXX"
}
fetch("http://XX.XX.XX.XX/v1/shipping", {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({bodyReq}),
})
.then(response => {response.json()
console.log(response, 'Response')})
.then(
(response) => {
this.setState({
isLoaded: true,
items: response.items
});
console.log(response, 'Response')
},
(error) => {
this.setState({
isLoaded: true,
error
});
console.log(error, 'RESerror')
}
)
}
This is the response I'm expecting from the API
{
"code": 201,
"error_code": 0,
"msg": [
{
"bu": "XXXX",
"carton_no": "XXXXXX",
"container_no": "XXXXXX",
"container_type": null,
"cust_no": "XXXXXX",
"emp_no": "XXXXXX",
"group_name": "XXXXXX",
"in_station_time": "XXXX-XX-XX XX:XX:XX",
"line_name": "XXXXXX",
"mo_number": "XXXXXX",
"model_name": "XXXXXX",
"pallet_no": "XXXXXX",
"plate_no": null,
"po_number": "XXXXXX",
"qa_no": "N/A",
"serial_number": "XXXXXX",
"ship_address": "XXXXXX",
"ship_mothod": "XXXXXX",
"version_code": "XXXXXX"
},
{
"bu": "XXXX",
"carton_no": "XXXXXX",
"container_no": "XXXXXX",
"container_type": null,
"cust_no": "XXXXXX",
"emp_no": "XXXXXX",
"group_name": "XXXXXX",
"in_station_time": "XXXX-XX-XX XX:XX:XX",
"line_name": "XXXXXX",
"mo_number": "XXXXXX",
"model_name": "XXXXXX",
"pallet_no": "XXXXXX",
"plate_no": null,
"po_number": "XXXXXX",
"qa_no": "N/A",
"serial_number": "XXXXXX",
"ship_address": "XXXXXX",
"ship_mothod": "XXXXXX",
"version_code": "XXXXXX"
}
],
"request": "POST /v1/shipping"
}
*note: I had to censure some data because is confidential data from the enterprise.