Home > PHP Framework > Laravel > body text

How to use middleware to implement cross-origin resource sharing (CORS) in Laravel

WBOY
Release: 2023-11-02 13:57:28
Original
1454 people have browsed it

How to use middleware to implement cross-origin resource sharing (CORS) in Laravel

How to use middleware to implement cross-domain resource sharing (CORS) in Laravel

Overview:

Cross-domain resource sharing (CORS) is a A browser mechanism that allows web applications to share resources under different domain names. Laravel, a popular PHP framework, provides a convenient way to handle CORS by using middleware to handle cross-domain requests.

This article will introduce you to how to use middleware to implement CORS in Laravel, including how to configure middleware, set allowed domain names and request methods, and provide specific code examples.

Step 1: Create CORS middleware

First, we need to create a middleware to handle CORS. Use the following command in the terminal to generate a new middleware file:

php artisan make:middleware CorsMiddleware

This command will be in the app/Http/Middleware directory Generate a file named CorsMiddleware.php.

Open the CorsMiddleware.php file and modify the handle method as follows:

public function handle($request, Closure $next)
{
    $response = $next($request);
    
    $response->header('Access-Control-Allow-Origin', '*');
    $response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    $response->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    
    return $response;
}
Copy after login

In this middleware, we set three response headers, They are: Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers. Access-Control-Allow-Origin Allows cross-domain access from all sources, and you can also set specific domain names as needed. Access-Control-Allow-MethodsDefine the allowed request methods. Here we set the common GET, POST, PUT, DELETE and OPTIONS. Access-Control-Allow-HeadersThe allowed request headers include Content-Type and Authorization.

Step 2: Register CORS middleware

Open the app/Http/Kernel.php file, find the $middleware array, and add it to the array Add the following line of code:

protected $middleware = [
    // ...
    AppHttpMiddlewareCorsMiddleware::class,
];
Copy after login

The above code will add the CorsMiddleware middleware to the global middleware stack so that it can be applied to every request.

Step 3: Use CORS middleware

In order to verify whether our CORS middleware is valid, we can use it in an API route. In the routes/api.php file, add a GET route and use CorsMiddlewaremiddleware for this route:

Route::get('/test', function () {
    return response()->json(['message' => 'Hello World']);
})->middleware('cors');
Copy after login

This route will return a message containing "Hello World" message's JSON response.

Step 4: Verify CORS settings

Now we can use any client that supports cross-domain access, such as a browser or REST client for verification. In the browser's development tools, we can see the response header information.

For example, on the Chrome browser, open the developer tools, switch to the "Network" tab, and then access the route /api/test we defined in step three. In the response headers, we should see Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headerssetting.

If everything is fine, you should be able to send HTTP requests from different domain names and get responses successfully.

Conclusion:

By using middleware, the Laravel framework provides a simple way to achieve cross-domain resource sharing. This article details how to create CORS middleware, register middleware, and use middleware to handle cross-domain requests. Hope this article can help you implement CORS in Laravel and provides enough code examples for your reference.

The above is the detailed content of How to use middleware to implement cross-origin resource sharing (CORS) in Laravel. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template