【问题标题】:CORS middlware running on preflight OPTIONS request but not on main requestCORS 中间件在预检 OPTIONS 请求上运行,但不在主请求上
【发布时间】:2017-04-20 22:02:40
【问题描述】:

我创建了一个处理我的 CORS 请求的中间件:

    <?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)
    {
      $headers = [
           'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
           'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization',
           'Access-Control-Allow-Origin' => '*'
       ];

     $response = $next($request);
     foreach ($headers as $key => $value){
       $response->headers->set($key, $value);
      }
     return $response;
    }
}

我已将其添加到我的kernel.php

'api' => [
        'throttle:60,1',
        'bindings',
        'cors'
    ],

当我向/user 发出GET 请求时,一切正常,但是当我向/api/answers 发出POST 请求时,我收到一个CORS 错误:XMLHttpRequest cannot load http://localhost:8000/api/answers. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.。两者都在我的api.php

    <?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group(['middleware' => ['auth:api']], function () {
    Route::get('/user', function (Request $request) {
        $user = $request->user();
        $user->load('locations.company');
        $user->load([
            'questionlists' => function ($query) {
                $query->with('questions.type');
                $query->with('difficulty');
            }
        ]);

        $amountOfCompletes = count($user->completes);
        $user->amountOfCompletes = $amountOfCompletes;
        return $user;
    });

    Route::resource('answers', 'AnswersController');
});

【问题讨论】:

标签: php laravel api http-headers middleware


【解决方案1】:

如果您尚未将中间件定义为路由中间件,请使用类引用

'api' => [
        'throttle:60,1',
        'bindings',
        App\Http\Middleware\Cors::class
    ],

【讨论】:

  • 抱歉,我有:'cors' =&gt; \App\Http\Middleware\Cors::class, 我尝试将其添加到帖子中,但我的光标一直在 SO 的编辑器中跳跃
  • 您能否通过将 dd 添加到中间件来检查并确认中间件是否被调用或被绕过?我也建议使用 laravel-cors 包github.com/barryvdh/laravel-cors
  • 不幸的是,那个包对我不起作用,dd 没有做任何事情
  • ok,请问中间件handle方法是不是在handle方法中使用dd调用了?
  • 当我echo 时,它会在我的预览选项卡中显示选项请求,但不会显示其他请求。 dd 也没有出现
猜你喜欢
  • 2014-09-03
  • 2018-11-27
  • 2015-08-04
  • 2019-10-03
  • 2019-07-14
  • 2021-02-21
  • 2020-04-09
  • 2019-08-29
  • 2014-08-02
相关资源
最近更新 更多