What is CORS?

CORS stands for Cross Origin Resource Sharing. Origin consists of protocol, domain and port number such as https://hogehoge.com:443. Therefore, CORS means allowing an web application on a certain origin (e.g. https://hogehoge.com) to access an web application on a different origin (e.g. https://fugafuga.com).

Why is CORS necessary?

In order to prevent cross site scripting (XSS) and cross site request forgeries, JavaScript’s asynchronous communication such as Ajax follows the same origin policy, which bans access to a different origin. Without CORS configuration, web applications can not access a different origin.

What is required to enable CORS?

The simplest method to enable CORS is to add Access-Control-Allow-Origin:* to the response header from WEB servers, which allows CORS from any source. If you want to limit the source, you should specify the domain in the configuration such as Access-Control-Allow-Origin:https://hogehoge.com. You should note that a domain has to be specified if an http request includes cookie information.

How to enable CORS on Laravel

You can use an middleware that adds Access-Control-Allow-Origin to an http response header.

  1. create an middleware
$ php artisan make:middleware Cors

<?XML:NAMESPACE PREFIX = «[default] http://www.w3.org/2000/svg» NS = «http://www.w3.org/2000/svg» />

2.Edit the middleware

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')

    }
}

3.Add the middleware to Kernel.php

protected $routeMiddleware = [
        'auth'          => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic'    => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings'      => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can'           => \Illuminate\Auth\Middleware\Authorize::class,
        'guest'         => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed'        => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle'      => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'cors'          => \App\Http\Middleware\Cors::class, // added
    ];

4.Set the middleware to routes

Route::middleware(['cors'])->group(function () {
    Route::post('/hogehoge', 'Controller@hogehoge');
});

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Любишь мемасики?

Подпишись на мой телеграм-канал!

Открыть
Закрыть