首页 > 解决方案 > 请求的资源上存在 Vue js Access-Control-Allow-Origin' 标头

问题描述

我有一个在前端运行 Vue 的 laravel 应用程序。该应用程序在 localhost:8000 上运行,在 Vue 端,我正在尝试从另一个 API 获取数据,例如https://someapi.com/。但是,我收到此错误,Access to XMLHttpRequest at 'https://someapi.com/' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

关于错误的研究让我想到了这个解决方案这个这个以及其他解决方案,但没有一个对我有用。

我创建了中间件:

<?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)
    {
        header("Access-Control-Allow-Origin: *");

        $headers = [
         'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
         'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if ($request->getMethod() == "OPTIONS") {
            return response()->make('OK', 200, $headers);
        }
        
        $response = $next($request);
        foreach ($headers as $key => $value) {
            $response->header($key, $value);
        }
        return $response;
    }
}


然后将其添加到 Kernel.php 中的 routemiddleware 数组中:

   protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
       
        'cors' => \App\Http\Middleware\CORS::class,
    ];

然后用它保护欢迎路线:

Route::middleware(['auth','cors'])->group(function () {
    Route::get('/', function () {
        return view('welcome');
    });
});

标签: javascriptlaravelvue.jscors

解决方案


推荐阅读