对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。 => Cors/Laravel
Posted
技术标签:
【中文标题】对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。 => Cors/Laravel【英文标题】:Response to preflight request doesn't pass access control check: It does not have HTTP ok status. => Cors/Laravel 【发布时间】:2020-02-11 03:30:20 【问题描述】:我目前正在编写一个通过 axios post req 与 API 对话的应用程序。以便收到响应。
我有一个 .vue 组件,其内容是具有给定规格的表单。 我通过 composer 安装了 CORS,设置了我的 cors.php 并在我的 kernel.php 中添加了所有必需的内容。
我的 Vue 存储在 .blade 中。 php 视图。
每次,当我尝试发送数据时,我都会收到 cors 的错误消息:
'http://myurl//'来自 来源 'http://api.laragon:8090' 已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:它 没有 HTTP ok 状态。
数据是通过表单发送的,当点击提交按钮时运行这个方法:
formSubmit(e)
const url="x";
e.preventDefault();
let currentObj = this;
this.axios
.post(url,
age: this.age,
claimantType: this.claimantType,
// zipcode: this.zipcode,
mcMax: 3,
icdCount: 1,
iCDCountInitialIllnesses: 0, //fix:0
uniqueVisitedDoctorsCount: 1, //fix:1
daysBetweenAccidentAndAC: 20, //fix:20
daysInHospital: 0, //fix:0
s13_4_only: 0 //fix:0 => 1, if only! selected
)
.then(function(response)
currentObj.output = response.data;
)
.catch(function(error)
currentObj.output = error;
console.log(error);
);
/config/app.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL', null),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
Barryvdh\Cors\ServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Arr' => Illuminate\Support\Arr::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'Str' => Illuminate\Support\Str::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
],
];
/config/cors.php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,
];
内核.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\Barryvdh\Cors\HandleCors::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
web.php
Route::get('/', function()
return view('start');
);
Route::get('/home', function ()
return view('home');
);
使用这个 tut 进行 cors 设置: https://github.com/barryvdh/laravel-cors
【问题讨论】:
我的猜测是您没有正确配置跨域资源共享 (cors.php),因为您的错误是“已被 CORS 策略阻止”。我非常怀疑错误是否在您发布的代码中。 在您发送 CORS 标头的位置显示您的中间件。另外,在你的刀片文件中使用像 Vue 这样的前端框架对我来说似乎很奇怪。你应该有一个单独的 Vue 项目,并有 Lumen(Laravel 的微框架)作为后端。 @Martin & rest,我编辑了我的帖子并添加了额外的 .php 配置文件(不要怀疑两个 cors,我尝试使用不同的提供程序) @lafllamme 你的问题解决了吗?我也有同样的问题 【参考方案1】:检查消息对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。
这意味着您的选项方法没有响应 2xx 状态代码。检查你的 API 配置是否有问题,并检查 Laravel API 是否有维护模式。
使用php artisan up
禁用维护模式。
【讨论】:
我完全明白你的意思,但我不知道如何实现这一点。我用我的 cors.php 和中间件编辑了我的帖子 - 我希望这能稍微启发这个问题 @lafllamme 这与 CORS 策略无关,但选项未响应 2xx,请检查路径存储/框架以获取文件名。如果有该文件,则说明您已开启维护模式。 命令给出:“应用程序已经启动。” & storage/framework 只包含 .gitignore 文件,包括缓存、会话、测试、视图文件夹 你能在浏览器上打开开发者工具,给我们一个端点的响应,以及相关的状态码吗? 查看我的帖子,我已添加控制台日志【参考方案2】:您没有 CORS 政策。
安装这个“composer require spatie/laravel-cors”然后放这个中间件,错误就会消失
// app/Http/Kernel.php
protected $middleware = [
...
\Spatie\Cors\Cors::class
];
【讨论】:
我已经与两个不同的 cors 提供商合作过 - 你会检查我编辑过的帖子吗? @lafllamme 你找到解决方案了吗?【参考方案3】:虽然我没有收到 404 错误(这可能是您的第一个问题),但我收到了相同的“响应预检...状态不正常”错误。
在我的例子中,处理请求的 API 控制器正在验证请求信息。它使用验证功能检查所需信息。由于我没有在我的请求中发布必填字段,因此验证失败并且服务器没有响应 HTTP 状态 ok。
所以你可以检查你的 API 控制器。
【讨论】:
【参考方案4】:想到的唯一解决方案是将中间件 Barry 放在内核文件的中间件之上...
还没有尝试过 Spatie pack,告诉我你是否成功...
也尝试管理预检...像两个响应
if ($request->isMethod("OPTIONS"))
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
// return $response('');
//$request->headers->set('Accept', 'application/json');
$response = $next($request);
【讨论】:
以上是关于对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。 => Cors/Laravel的主要内容,如果未能解决你的问题,请参考以下文章
CORS 错误:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态
domain.com 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态
Spring Boot,CORS 问题:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态
被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP OK 状态
对预检请求的响应未通过访问控制检查:在标头中使用身份验证时,它没有 HTTP ok 状态 [关闭]
React Express Fetch Post CORS 错误:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态