javascript - Larvel 5.8:从 javascript 但不是从浏览器调用路由时忽略中间件
问题描述
我有一个简单的“cors”中间件
public function handle($request, Closure $next)
{
// return response()->json(['message' => 'Not Found.'], 404);
if (config('app.env') !== 'production') {
return $next($request)
->header("Access-Control-Allow-Origin", "*")
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
} else {
return $next($request);
}
}
routes/api.php
我以这种方式添加了中间件:
<?php
// Rotte /api/v1
Route::group(['prefix' => 'v1', 'middleware' => ['cors'] ], function () {
... wrapping all /api/v1 routes
}
当我从浏览器访问网址时,我在开发者选项中看到
但是,当 javscript 调用相同的 url 时,“选项”预检请求失败
从源“ https://localhost:3000 ”访问“ https://project.local/api/v1/customer ”的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否请求的资源上存在“Access-Control-Allow-Origin”标头。
我究竟做错了什么?
请注意,要求 laravel 列出我的路线,实际上表明应用了 cors !
php artisan route:list --path api/v1/
+--------+-----------+-------------------------------+------------------+----------------------------------------------------------+---------------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+-----------+-------------------------------+------------------+----------------------------------------------------------+---------------------+
| | GET|HEAD | api/v1/customer | customer.index | App\Http\Controllers\CustomerController@index | api,cors,jwt.verify |
| | POST | api/v1/customer | customer.store | App\Http\Controllers\CustomerController@store | api,cors,jwt.verify |
| | GET|HEAD | api/v1/customer/{customer} | customer.show | App\Http\Controllers\CustomerController@show | api,cors,jwt.verify |
| | PUT|PATCH | api/v1/customer/{customer} | customer.update | App\Http\Controllers\CustomerController@update | api,cors,jwt.verify |
| | DELETE | api/v1/customer/{customer} | customer.destroy | App\Http\Controllers\CustomerController@destroy | api,cors,jwt.verify |
解决方案
请使用其他标头更新您的中间件,
if (config('app.env') !== 'production') {
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, Authorization, X-XSRF-TOKEN, X-Requested-With');
这应该可以解决问题。
推荐阅读
- visual-studio-code - VSCode 无法从不同目录导入 python 模块
- php - 如何检测 mime 中的电子邮件主题是否在 PHP 上解码?
- python - 部署到 EC2 setuptools_rust 时出现 Python 管道错误
- swift - 滑动 NSSlider 阻止键的 NSEvent 监视,反之亦然,如何捕捉它们一致
- tensorflow - 从目录重新加载 Keras-Tuner Trials
- math - 在 PARI GP 中传递用户定义函数之外的值
- c - 有没有办法从返回的 char* 中安全地收集数据?
- python - 如何从python列表中的dict中提取值
- r - 按多列分组并按顺序标记组?
- python - 试图随机化哪个函数在 discord.py 中运行但发生错误