简体   繁体   中英

Making a delete request using Axios to Laravel API throws an error but works fine in insomnia

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

In your package.json file of frontend/client folder try to add proxy like this

  "name": "app_name",
  "proxy": "http://127.0.0.1:8000"

The issue is resolved by adding Laravel Cors package in the laravel App (API Provider).

Following is the link to Laravel Cors pakage

https://github.com/fruitcake/laravel-cors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM