【发布时间】:2020-07-23 10:33:24
【问题描述】:
我最近想将 VueJS 前端应用程序集成到我的 Laravel 应用程序中。首先,我在Laravel 中安装了fruitcake/laravel-cors 库,并使用Vue Axios 建立了从Vue.js 到Laravel 的连接。现在所有类型的请求都可以正常工作(POST、PUT、UPDATE...),GET 除外。规格如下:
Laravel 应用:
-
中间件:
protected $middleware = [ //... Rest of the middleware //CORS middleware \Fruitcake\Cors\HandleCors::class ]; -
CORS 配置文件:
return [ /* * You can enable CORS for 1 or multiple paths. * Example: ['api/*'] */ 'paths' => ['api/*'], /* * Matches the request method. `[*]` allows all methods. */ 'allowed_methods' => ['POST', 'GET', 'OPTIONS', 'PUT', 'PATCH', 'DELETE'], /* * Matches the request origin. `[*]` allows all origins. */ 'allowed_origins' => explode(' ', env('API_ALLOWED_ORIGINS')), /* * Matches the request origin with, similar to `Request::is()` */ 'allowed_origins_patterns' => [], /* * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers. */ 'allowed_headers' => ['*'], /* * Sets the Access-Control-Expose-Headers response header with these headers. */ 'exposed_headers' => [], /* * Sets the Access-Control-Max-Age response header when > 0. */ 'max_age' => 0, /* * Sets the Access-Control-Allow-Credentials header. */ 'supports_credentials' => false, ]; -
ENV 文件
API_ALLOWED_ORIGINS=http://localhost:8080 -
路线:
Route::get('/something', 'SomeComtroller@someAction');
Vue.JS 应用程序:
-
axios 获取方法:
get(resource, slug = "") { return Vue.axios.get(`${resource}/${slug}`).catch(error => { // console.log(error); throw new Error(`ApiService ${error}`); }); }, -
API 调用
ApiService.get("something") .then(({ data }) => { console.log(data); }) .catch(({ response }) => { console.log(response.data); });
浏览器输出:
Access to XMLHttpRequest at 'http://laravel.app/api/something' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
与POST 相同的路由正在工作,但现在与GET 一起工作。
更新
开发者控制台网络标签:
HTTP/1.1 301 Moved Permanently
Date: Fri, 10 Apr 2020 16:54:26 GMT
Server: Apache
Location: http://laravel.app/api/something
Content-Length: 244
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
X-Pad: avoid browser bug
【问题讨论】: