php - Laravel Cors 中间件不适用于 POST 请求

标签 php laravel cors

所以我正在使用 Laravel 5.8作为 APIReactJS看法。

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

Access to fetch at 'http://localhost:8000/api/posts' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.



所以我在我的 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 .有人已经遇到这个问题了吗?

最佳答案

将您的中间件更改为此

<?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 Link here

关于php - Laravel Cors 中间件不适用于 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57042612/

相关文章:

php - 如何在开发人员之间使用具有不同数据库配置的 Git?

php - 使用 mysqli 计算行数并传递信息

Laravel/Lumen 更新至 5.5,路由损坏

php - LARAVEL:MYSQL:违反完整性约束:1452 无法添加或更新子行:外键约束失败

javascript - 如何在 AngularJs 中启用 CORS

javascript - "Cross origin requests are only supported for HTTP."加载本地文件时出错

javascript - Elasticsearch https cors 已启用,但仍然收到 No 'Access-Control-Allow-Origin' header is present on the requested resource

php - WP-ADMIN 重定向循环

javascript - 多次使用 MySQLi 查询结果数组

php - 如何检查给定日期是否晚于 3 天?