Cross domain Solution in laravel Development
- 2021-08-12 02:10:05
- OfStack
Preface
As we all know, when we develop with laravel, especially when the front and back ends are completely separated, because the front-end project runs on the designated port of our own machine (or other people's machines), such as localhost: 8000, and the laravel program runs on another port, it is cross-domain, and because of the browser's homology policy, cross-domain requests are illegal. In fact, this problem is very easy to solve, only need to add a middleware can be. The following words are not much to say, let's take a look at the detailed solutions with this site 1.
Solution:
1. Create a new middleware
php artisan make:middleware EnableCrossRequestMiddleware
2. Writing 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('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 you allow to cross domains, and can be modified by yourself.
3. Then 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, where the middleware registered belongs to the global middleware.
Then you will find that the front-end page can already send cross-domain requests.
One more method to options request is normal, because the browser must first determine whether the server allows the cross-domain request.
Summarize