Cross-origin solution in laravel development, laravel
Preface
As we all know, when we use laravel for development, especially when the frontend and backend are completely isolated, because the frontend project runs on the specified port (or another machine) of our machine ), for example, localhost: 8000, while the laravel program runs on another port, so that cross-origin occurs. Due to the browser's same-origin policy, cross-origin requests are invalid. In fact, this problem is well solved. You only need to add a middleware. I will not talk about it much below. Let's take a look at the detailed solution along with the small Editor.
Solution:
1. Create a Middleware
php artisan make:middleware EnableCrossRequestMiddleware
2. Write middleware content
<?phpnamespace App\Http\Middleware;use Closure;class EnableCrossRequestMiddleware{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : ''; $allow_origin = [ 'http://localhost:8000', ]; if (in_array($origin, $allow_origin)) { $response->header('Access-Control-Allow-Origin', $origin); $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN'); $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated'); $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS'); $response->header('Access-Control-Allow-Credentials', 'true'); } return $response; }}
The $ allow_origin array variable is the list of cross-origin allowed. You can modify the variable by yourself.
3. register the middleware in the kernel file.
protected $middleware = [ // more App\Http\Middleware\EnableCrossRequestMiddleware::class, ];
Add the $ middleware attribute in the App \ Http \ Kernel class. The registered middleware is a global middleware.
Then you will find that the front-end page can send cross-origin requests.
It is normal that an additional request with the method of options is generated, because the browser must first determine whether the server permits the cross-origin request.
Summary
The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.