创建一个新的中间件:app/Http/Middleware/cors.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
将 cors 中间件添加到 app/Http/Kernel.php
protected $routeMiddleware = [
//default laravel middleware
'cors' => \App\Http\Middleware\Cors::class,
];
将新的 cors 中间件添加到您的路由
Route::get('/broadcast', function () {
broadcast(new hello());
});
})-> middleware('cors');
---注意---这现在将接受来自任何地方的请求。
这在 localhost 上很好,但是当您移动到实时服务器时,您需要更改:
->header('Access-Control-Allow-Origin', '*')
至
->header('Access-Control-Allow-Origin', 'http://www.yourdomain.com')
或者您需要创建一个 api 密钥以与每个请求一起传递,以便您可以拥有公共 api(不推荐,但这是一个可行的解决方法)