作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我正在使用 Laravel 5.8
作为 API
到 ReactJS
看法。
我已经创建了一个“cors”中间件,我在 Kernel.php 文件上注册了它,我在我正在使用的 api-routes 上使用它。我使用 GET 请求进行了测试并且它有效,但是当我使用 POST 请求进行测试时,我收到了 cors 错误:
Access to fetch at 'http://localhost:8000/api/posts' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Route::get('/posts', 'PostController@index')->middleware('cors');
Route::post('/posts', 'PostController@store')->middleware('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)
{
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');
}
}
'cors'
更新了“$routeMiddleware”数组中间件
'cors' => \App\Http\Middleware\Cors::class,
// 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
Link here
关于php - Laravel Cors 中间件不适用于 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57042612/
我是一名优秀的程序员,十分优秀!