首页 > 解决方案 > Laravel Cors 中间件不适用于 POST 请求

问题描述

因此,我将其Laravel 5.8用作视图。APIReactJS

我已经创建了一个“cors”中间件,我在Kernel.php文件上注册了它,我在我正在使用的 api-routes 上使用它。我使用 GET 请求进行了测试并且它有效,但是当我使用 POST 请求进行测试时,我得到了 cors 错误:

CORS 策略已阻止从源“ http: //localhost:8000/api/posts ”获取从“ http://localhost:3000 ”获取的访问权限:对预检请求的响应未通过访问控制检查:没有“访问权限” -Control-Allow-Origin' 标头存在于请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

所以我在我的api.php ("/routes/api.php") 上有:

Route::get('/posts', 'PostController@index')->middleware('cors');
Route::post('/posts', 'PostController@store')->middleware('cors');

我的cors.php中间件:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @return mixed
   */
  public function handle($request, Closure $next)
  { 
    return $next($request)
      ->header('Access-Control-Allow-Origin', '*')
      ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
      ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
  }
}

在我的Kernel.php ("/app/Http/Kernel.php") 上,我用'cors'中间件更新了 "$routeMiddleware" 数组

'cors' => \App\Http\Middleware\Cors::class, 

现在在我的 React 项目中,我的api.js(我在其中编写代码以发出请求):

// get Posts
export const getPosts = () => {
  return fetch('http://localhost:8000/api/posts')
    .then(res => res.json())
    .then(json => console.log(json))
    .catch(err => console.log(err));
}

// create new post
export const createPost = (post) => {

  return fetch('http://localhost:8000/api/posts',
  {
    method: 'post',
    headers: {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(post)
  })
  .then(res => res.json())
  .then(res => console.log(res));
}

我不明白为什么当我尝试时一切正常Get request,但是当我尝试时Post Request,我得到了CORS error。有人已经有这个问题了吗?

标签: phplaravelcors

解决方案


将您的中间件更改为此

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @return mixed
   */
  public function handle($request, Closure $next)
  {
    $domain = parse_url($_SERVER['HTTP_REFERER']);
    $host = '*';
    if (isset($domain['host'])) {
        $host = $domain['host'];
    }
    return $next($request)
      ->header('Access-Control-Allow-Origin', $host)
      ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
      ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization,     X-Requested-With, Application');
  }
}

但是一旦投入生产,您需要通过环境变量限制允许的主机。

你也可以barryvdh/laravel-cors 在这里使用链接


推荐阅读