我正在尝试使用 axios 从 VueJS 到 Laravel,这是我的 API。
我遇到了这个错误:
Access to XMLHttpRequest at 'http://api.test/api/events/1/' from origin >'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control->Allow-Origin' header is present on the requested resource.
Uncaught (in promise) Error: Network Error at createError (createError.js?2d83:16) at XMLHttpRequest.handleError (xhr.js?b50d:87)
我尝试创建一个名为“cors”的中间件,例如 here但它对我不起作用,或者我做得不好?
奇怪的事情?是与 Postman 合作。
感谢帮助! :)
最佳答案
Servers are used to host web pages, applications, images, fonts, and much more. When you use a web browser, you are likely attempting to access a distinct website (hosted on a server). Websites often request these hosted resources from different locations (servers) on the Internet. Security policies on servers mitigate the risks associated with requesting assets hosted on different server. Let's take a look at an example of a security policy: same-origin.
The same-origin policy is very restrictive. Under this policy, a document (i.e., like a web page) hosted on server A can only interact with other documents that are also on server A. In short, the same-origin policy enforces that documents that interact with each other have the same origin.
检查这个CORS为 Laravel 使用而制作的库。 安装简单:
$ composer require barryvdh/laravel-cors
$ php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
默认设置在 config/cors.php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,
];
allowedOrigins、allowedHeaders
和 allowedMethods
可以设置为 array('*')
以接受任何值。
要允许所有路由使用 CORS,请在 app/Http/Kernel.php
类的 $middleware
属性中添加 HandleCors 中间件:
protected $middleware = [
// ...
\Barryvdh\Cors\HandleCors::class,
];
如果您想在特定中间件组或路由上允许 CORS,请将 HandleCors 中间件添加到您的组:
protected $middlewareGroups = [
'web' => [
// ...
],
'api' => [
// ...
\Barryvdh\Cors\HandleCors::class,
],
];
关于laravel - CORS Laravel VueJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54218774/