Detailed explanation of cross-domain solutions in laravel development

黄舟
Release: 2023-03-16 20:56:01
Original
2247 people have browsed it

Preface

As we all know, 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 someone else's machine), such as localhost:8000, and the laravel program runs on another port, so it is cross-domain. However, due to the browser's same-origin policy, cross-domain requests are illegal. In fact, this problem is easy to solve, just add amiddleware. Not much to say below, let’s follow the editor to see the detailed solutions.

Solution:

1. Create a new middleware

php artisan make:middleware EnableCrossRequestMiddleware
Copy after login

2. Write the middleware content

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; } }
Copy after login

$allow_originArrayThe variable is your allowed cross-domain list and can be modified by yourself.

3. Then register the middleware in the kernel file

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

Add it to the $middleware attribute of the App\Http\Kernel class. The middleware registered here belongs to the global middleware.
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.

Summarize

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!