所以我使用Laravel 5.8作为API一个ReactJS视图。
我已经创建了一个“cors”中间件,我在Kernel.php文件上注册了它,我在我正在使用的 api-routes 上使用它。我使用 GET 请求进行了测试并且它有效,但是当我使用 POST 请求进行测试时,我收到了 cors 错误:
访问以获取“的http://本地主机:8000 / API /帖”从原点“的http://本地主机:3000 ”已被封锁的CORS政策:回应预检要求未通过访问控制检查:没有“访问-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');
Run Code Online (Sandbox Code Playgroud)
我的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');
}
}
Run Code Online (Sandbox Code Playgroud)
在我的Kernel.php ("/app/Http/Kernel.php") 上,我用我的'cors'中间件更新了 "$routeMiddleware" 数组
'cors' => \App\Http\Middleware\Cors::class,
Run Code Online (Sandbox Code Playgroud)
现在在我的 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));
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么当我尝试时一切正常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');
}
}
Run Code Online (Sandbox Code Playgroud)
但一旦投入生产,您需要通过环境变量限制允许的主机。
您也可以直接使用barryvdh/laravel-cors 此处的链接
| 归档时间: |
|
| 查看次数: |
6999 次 |
| 最近记录: |