【发布时间】:2019-11-24 07:48:49
【问题描述】:
所以我使用Laravel 5.8 作为API 到ReactJS 视图。
我已经创建了一个 'cors' 中间件,我在 Kernel.php 文件中注册了它,并且我在我正在使用的 api-routes 上使用它。我使用 GET 请求进行了测试,它可以工作,但是当我使用 POST 请求进行测试时,我得到了 cors 错误:
从源“http://localhost:3000”获取“http://localhost:8000/api/posts”的访问权限已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-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。有人遇到过这个问题吗?
【问题讨论】:
-
Access-Control-Allow-Origin: *不被浏览器接受,您需要指定允许的域。没有更多的小丑*