本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

CORS 中间件在预检 OPTIONS 请求上运行,但不在主请求上运行

发布于2024-11-30 20:11     阅读(499)     评论(0)     点赞(18)     收藏(1)


我创建了一个处理 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'
    ],

当我GET向 发出请求时/user,一切正常,但是当我POST向 发出请求时/api/answers,我收到 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');
});

解决方案


如果你还没有将中间件定义为路由中间件,请使用类引用

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


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.phpheidong.com/blog/article/558243/d1c77368272b8abc9981/

来源:php黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

18 0
收藏该文
已收藏

评论内容:(最多支持255个字符)