Error: Access to fetch at .... has been blocked by CORS
CORS stands for cross origin resource share. If use Javascript to fetch a endpoint and endpoin is not the same origin as the current page, may see the above error. Here origin is protocol + domain + port.
//host is https://examplea.com
<script>
let endpoint = "https://exampleb.com/create-order";
return fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(resp => {
if (!resp.ok) throw new Error('Network response was not ok');
return resp.json();
});
</script>
To solve the issue. For that end point of exampleb.com. the response needs to set headers such as
$response = $response->withHeader('Access-Control-Allow-Origin', "*");
return $response->withHeader('Access-Control-Allow-Headers', 'X-Requested-With,x-api-key, Content-Type, Accept, Origin, Authorization, X-Authorization-JWT, X-CSRF-Token')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
No comments:
Post a Comment