Hi I am creating a web app using create-react-app which consumes endpoints developed in laravel 5.
When I make a Delete request using axios to the server, I get this error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/carts/7?api_token={api_token}. (Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’) Whereas, when I send the same request on Insomnia (HTTP Rest Client), I donot get any error.
Here is the react code
handleDelete = ( cartId ) => {
const api_token = localStorage.getItem('jbs_user_api_token');
console.log("Delete cart item: ", cartId);
axios.delete(`carts/${cartId}?api_token=${api_token}`)
.then( res => {
console.log(res);
})
.catch( err => {
console.log(err);
});
}
Following is the endpoint in Laravel 5, the react app is making the aforementioned request to
Route::resource('carts', 'API\CartAPIController');
Here is the method (laravel) that handles the delete request
public function destroy($id)
{
$cart = $this->cartRepository->findWithoutFail($id);
if (empty($cart)) {
return $this->sendError('Cart not found');
}
$cart = $this->cartRepository->delete($id);
return $this->sendResponse($cart, __('lang.deleted_successfully', ['operator' => __('lang.cart')]));
}
Definitely, there is no error on the API (Backend) since the request works fine in insomnia. Plus both the applications (react and laravel) are served from localhost.
Please help
The issue is resolved by adding Laravel Cors package in the laravel App (API Provider).
Following is the link to Laravel Cors pakage