[英]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.嗨,我正在使用 create-react-app 创建一个 Web 应用程序,它使用在 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} .当我使用 axios 向服务器发出删除请求时,出现此错误跨域请求被阻止:同源策略不允许读取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.
(原因:未在 CORS 标头“Access-Control-Allow-Methods”中找到方法)然而,当我在 Insomnia(HTTP Rest Client)上发送相同的请求时,我没有收到任何错误。
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以下是 Laravel 5 中的端点,反应应用程序正在向
Route::resource('carts', 'API\CartAPIController');
Here is the method (laravel) that handles the delete request这是处理删除请求的方法(laravel)
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.当然,API(后端)上没有错误,因为请求在失眠时工作正常。 Plus both the applications (react and laravel) are served from localhost.
此外,两个应用程序(react 和 laravel)都是从 localhost 提供的。
Please help请帮忙
In your package.json file of frontend/client folder try to add proxy like this在前端/客户端文件夹的 package.json 文件中尝试添加这样的代理
"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).通过在 Laravel 应用程序(API 提供程序)中添加 Laravel Cors 包解决了该问题。
Following is the link to Laravel Cors pakage以下是 Laravel Cors 包的链接
https://github.com/fruitcake/laravel-cors https://github.com/fruitcake/laravel-cors
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.