Home  >  Article  >  PHP Framework  >  laravel cross-domain solution

laravel cross-domain solution

藏色散人
藏色散人forward
2019-10-22 13:26:393363browse

When we use laravel for development, especially when the front-end and back-end are completely separated, since the front-end project runs on the designated port of our own machine (it may also be other people's machines), such as localhost:8000, and the laravel program Running on another port makes it cross-domain, and due to the browser's same-origin policy, cross-domain requests are illegal. In fact, this problem is easy to solve, just add a middleware.

1. Create a new middleware

php artisan make:middleware EnableCrossRequestMiddleware

2. Write the middleware content

<?php
namespace 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(&#39;HTTP_ORIGIN&#39;) ? $request->server(&#39;HTTP_ORIGIN&#39;) : &#39;&#39;;
        $allow_origin = [
            &#39;http://localhost:8000&#39;,
        ];
        if (in_array($origin, $allow_origin)) {
            $response->header(&#39;Access-Control-Allow-Origin&#39;, $origin);
            $response->header(&#39;Access-Control-Allow-Headers&#39;, &#39;Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN&#39;);
            $response->header(&#39;Access-Control-Expose-Headers&#39;, &#39;Authorization, authenticated&#39;);
            $response->header(&#39;Access-Control-Allow-Methods&#39;, &#39;GET, POST, PATCH, PUT, OPTIONS&#39;);
            $response->header(&#39;Access-Control-Allow-Credentials&#39;, &#39;true&#39;);
        }
        return $response;
    }
}

$allow_origin array variable is you The list of allowed cross-domains can be modified by yourself.

3. Then register the middleware in the kernel file

    protected $middleware = [
        // more
        App\Http\Middleware\EnableCrossRequestMiddleware::class,
    ];

Add in the $middleware attribute of the App\Http\Kernel class. The middleware registered here belongs to the global middleware pieces.

Then you will find that the front-end page can already send cross-domain requests.

It is normal that there will be one more request with method set to options, because the browser must first determine whether the server allows the cross-domain request.

For more Laravel related technical articles, please visit the Laravel Framework Getting Started Tutorial column to learn!

The above is the detailed content of laravel cross-domain solution. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete