php - Laravel Cors 中间件不适用于 POST 请求
问题描述
因此,我将其Laravel 5.8
用作视图。API
ReactJS
我已经创建了一个“cors”中间件,我在Kernel.php文件上注册了它,我在我正在使用的 api-routes 上使用它。我使用 GET 请求进行了测试并且它有效,但是当我使用 POST 请求进行测试时,我得到了 cors 错误:
CORS 策略已阻止从源“ http: //localhost:8000/api/posts ”获取从“ http://localhost:3000 ”获取的访问权限:对预检请求的响应未通过访问控制检查:没有“访问权限” -Control-Allow-Origin' 标头存在于请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
所以我在我的api.php ("/routes/api.php") 上有:
Route::get('/posts', 'PostController@index')->middleware('cors');
Route::post('/posts', 'PostController@store')->middleware('cors');
我的cors.php中间件:
<?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)
{
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, Accept, Authorization, X-Requested-With, Application');
}
}
在我的Kernel.php ("/app/Http/Kernel.php") 上,我用'cors'
中间件更新了 "$routeMiddleware" 数组
'cors' => \App\Http\Middleware\Cors::class,
现在在我的 React 项目中,我的api.js(我在其中编写代码以发出请求):
// get Posts
export const getPosts = () => {
return fetch('http://localhost:8000/api/posts')
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.log(err));
}
// create new post
export const createPost = (post) => {
return fetch('http://localhost:8000/api/posts',
{
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(post)
})
.then(res => res.json())
.then(res => console.log(res));
}
我不明白为什么当我尝试时一切正常Get request
,但是当我尝试时Post Request
,我得到了CORS error
。有人已经有这个问题了吗?
解决方案
将您的中间件更改为此
<?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)
{
$domain = parse_url($_SERVER['HTTP_REFERER']);
$host = '*';
if (isset($domain['host'])) {
$host = $domain['host'];
}
return $next($request)
->header('Access-Control-Allow-Origin', $host)
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
}
}
但是一旦投入生产,您需要通过环境变量限制允许的主机。
你也可以barryvdh/laravel-cors
在这里使用链接
推荐阅读
- java - JPA 中的生成模式
- postgresql - Postgresql 11 根据外键关系中主表中的列对详细表进行分区
- java - java - 如何将值从java类传递到java框架?
- pandas - AttributeError:“索引”对象没有属性“左”
- linux - 提取包含两个模式的行
- reactjs - Reactjs Map 功能无法显示搜索记录
- reactjs - 具有多个名称属性的 React-Datepicker handleChange
- machine-learning - 强化学习中的 Q、V(价值函数)和奖励之间究竟有什么区别?
- python - 如何创建另一个数据框的第一个有效值的熊猫数据框?
- laravel - Laravel 返回一个包含第一个模型重复的集合