Vue Axios没有'Access-Control-Allow-Origin'标头

时间:2019-12-12 19:45:37

标签: api vue.js cors axios

我正在尝试学习如何使用Laravel和Vue来使用外部api。我正在关注VueJs documentation example,但遇到了问题。我不断收到此错误:

Access to XMLHttpRequest at 'https://api.coindesk.com/v1/bpi/currentprice.json' from origin 'http://myDomain.test' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

app.js:653 Uncaught (in promise) Error: Network Error
    at createError (app.js:653)
    at XMLHttpRequest.handleError (app.js:188)

我尝试按照说明from this other answer进行操作,但是我没有运气。有人可以告诉我我做错了吗?我正在开发中,并且正在我的本地主机上运行它。

这是我的代码:

mounted() {
            console.log('hit');

            axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
                .then(response => {
                    console.log(response);
            });
        }

编辑:

我决定尝试使用本教程https://medium.com/@petehouston/allow-cors-in-laravel-2b574c51d0c1

来实现cors中间件

这是我所做的:

Cors中间件:

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', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Token-Auth, Authorization');
    }

}

内核:

protected $routeMiddleware = [
    'auth' => \App\Http\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,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'cors' => \App\Http\Middleware\Cors::class,

];

网络路线:

Route::get('/', function () {
return view('layouts.app');})->middleware('cors');

当我在“开发”选项卡中检查网络时,将显示以下内容: enter image description here

这导致我收到这个新错误:

Access to XMLHttpRequest at 'https://min-api.cryptocompare.com/data/all/coinlist' from origin 'http://myDomain.test' has been blocked by CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.

0 个答案:

没有答案