gpt4 book ai didi

laravel - GET 请求结果导致 Lumen 8 中出现 CORS 错误

转载 作者:行者123 更新时间:2023-12-05 01:31:04 25 4
gpt4 key购买 nike

当 Axios 向我的 Lumen 应用程序发送 GET HTTP 时,我遇到了这个 CORS 问题,发送 POST HTTP 似乎没问题。我有这个处理 CORS 的中间件,下面是代码

<?php namespace App\Http\Middleware;

use Closure;

class CorsMiddleware{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];

if ($request->isMethod('OPTIONS'))
{
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}

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

return $response;
}
}

然后添加到bootstrap/app.php

$app->middleware([
App\Http\Middleware\CorsMiddleware::class, // cors middleware
]);

对于 POST 请求,一切正常,但在执行 GET 请求时,会发生 CORS 错误。非常感谢任何帮助和想法,在此先感谢。

我的前端应用程序在 http://localhost:3000 (NUXT) 上运行,而 Lumen 应用程序在 http://localhost:8000 上运行

下图是错误的截图。 enter image description here

最佳答案

这个问题的另一个解决方案是:

App\Providers 目录中创建 CatchAllOptionsRequestsProvider.php

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

/**
* If the incoming request is an OPTIONS request
* we will register a handler for the requested route
*/
class CatchAllOptionsRequestsProvider extends ServiceProvider {
public function register()
{
$request = app('request');
if ($request->isMethod('OPTIONS'))
{
app()->options($request->path(), function() { return response('', 200); });
}
}
}

CorsMiddleware.php

<?php

namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//Intercepts OPTIONS requests
if($request->isMethod('OPTIONS')) {
$response = response('', 200);
} else {
// Pass the request to the next middleware
$response = $next($request);
}

// Adds headers to the response
$response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE');
$response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
$response->header('Access-Control-Allow-Origin', '*');

// Sends it
return $response;
}
}

bootstrap/app.php中添加以下代码

$app->middleware([
App\Http\Middleware\CorsMiddleware::class
]);

$app->register(App\Providers\CatchAllOptionsRequestsProvider::class);

关于laravel - GET 请求结果导致 Lumen 8 中出现 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66558151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com