外部 API 的 CORS 问题 - 通过 PostMan 工作,但不能通过 Axios 进行 HTTP 请求 [英] CORS Issue with external API - Works via PostMan but not HTTP request with Axios

查看:43
本文介绍了外部 API 的 CORS 问题 - 通过 PostMan 工作,但不能通过 Axios 进行 HTTP 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在开发一个涉及汽车数据的新 Laravel 项目,并找到了一个免费的查找 API.

Working on a new Laravel project that involves car data and found a free look up API.

http://www.carqueryapi.com/documentation/api-usage/

一个示例端点是:

https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes

这在具有普通 GET 请求的 PostMan 上运行良好.

This works fine on PostMan with a normal GET request.

但是在使用 Axios 的 Vue.js 中:

However in Vue.js using Axios:

getAllMakes: function() {
    axios.get("https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes").then(function(response) {
        console.log(response);
    });
}

我遇到了 CORS 问题:

I get a CORS issue:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

有什么我可以做的吗?或者某些 API 被阻塞了?

Is there anything I can do? Or some the API is blocking?

推荐答案

你可以使用这个来修复这个错误

You can fix this error using this

    return axios(url, {
      method: 'GET',
      mode: 'no-cors',
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json',
      },
     credentials: 'same-origin',
    }).then(response => {
      console.log(response);
    })

在你的 API 中请添加一个 cors 中间件

In your API please add a cors 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)
{

    header("Access-Control-Allow-Origin: *");

    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
    ];
    if($request->getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        return Response::make('OK', 200, $headers);
    }

    $response = $next($request);
    foreach($headers as $key => $value)
        $response->header($key, $value);
    return $response;
 }

}

在 app\Http\Kernel.php 中添加中间件

Add Middleware in app\Http\Kernel.php

 protected $routeMiddleware = [
    'cors' => 'App\Http\Middleware\CORS',
];

然后你可以在路由中使用它

Then you can use this in routes

Route::get('/', function () {`enter code here`
})->middleware('cors');

这篇关于外部 API 的 CORS 问题 - 通过 PostMan 工作,但不能通过 Axios 进行 HTTP 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆