SERVER/LARAVEL & PHP

Laravel + vuejs Access to XMLHttpRequest at been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 오류 해결

나나나나나나나ㅏ나난ㄴ나ㅏ나나 2021. 1. 21. 16:38
728x90

환경

 

  • php 7.4 laravel
  • vuejs

CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 가 뜨고 3시간인가 4시간 지난 후 오류를 수정했다ㅠㅠ

 

1. Cors 미들웨어 생성

있으신 분은 그냥 있는거 사용하시면된다!

php artisan make:middleware Cors

 

2. Cors 미들웨어에서 헤더 생성

 

CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 이제 그만보고싶다ㅠㅠㅠㅠㅠ

app/Http/Middleware/Cors.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {

        //ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,PUT,DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Authorization',
            'Access-Control-Allow-Origin' => '*'
        ];
        if ($request->getMethod() == "OPTIONS"){
            //The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return response()->json('OK',200,$headers);
        }
        $response = $next($request);
        foreach ($headers as $key => $value) {
            $response->header($key, $value);
        }
        return $response;
    }
}

 

3. Cors 클래스 추가

app/Http/Kenel.php

protected $middleware = [
	...
    
	\App\Http\Middleware\Cors::class,
    
    ...
    ...
    
]

 

하면 마법처럼 오류가 사라지는걸 볼 수 있다!

 

CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 저번에도 고생한거같은데 이제 그만보고싶다 🤦🏻‍♀️

728x90