当我尝试使用 Axios 调用 Instagram API 时,我得到 "blocked by CORS policy"

I'm getting "blocked by CORS policy" when I try to call Instagram API using Axios

我正尝试在一个以 Vue 作为前端的 Laravel 应用程序中从我的 Instagram 帐户中获取一些图像。当我尝试在独立的 Vue 应用程序中执行此操作时,它运行良好,但是当我使用 Laravel 执行此操作时,我收到一条消息说 "has been blocked by CORS policy: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response."

我正在使用 Laravel 5.8 以及其中的 Vue 和 Axios,并且我正在使用 Homestead 作为我的本地主机服务器。

我已经尝试了很多在这里和 Google 上找到的技巧,但都没有成功。基本上,我正在尝试最基本的 Axios 调用

        beforeMount() {
            axios.get('https://api.instagram.com/v1/users/self/media/recent/?access_token=[MY_ACCESS_TOKEN]').then(response => console.log(response))
        }

我已经在 Laravel 上创建了一个 Cors 中间件,并在 Axios 上尝试了很多 headers 设置。

我基本上是在尝试检索我的 Instagram 帖子列表并绕过该 cors / x-csrf 错误。

您对 Instagram 端点的 AJAX 请求必须作为 jsonp 请求发送,这意味着请求的 dataType 必须是 jsonp

This blob 包含在 axios.

中使用 jsonp 的示例

这是向 Instagram 端点发送数据类型为 AJAXAJAX 请求的示例。

$.ajax({
    url: "https://api.instagram.com/v1/users/self/media/recent/?access_token=[MY_ACCESS_TOKEN]",
    type: "GET",
    crossDomain: true,
    dataType: "jsonp",
    success: function(response){
        console.log(response);
    }
});

Laravel 自动将 X-CSRF-TOKEN header 应用于所有 axios 请求。这样您就可以与您的应用程序通信,而不必每次都为 POST、PUT、DELETE 等

传递 CSRF 令牌

resources/js/bootstrap.js(默认设置)

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

您应该可以通过执行以下操作来删除违规的 header:

beforeMount() {

    // create a new instance so we don't delete the csrf token for other requests
    let instance = axios.create();

    // delete the x-csrf-token header
    delete instance.defaults.headers.common['X-CSRF-TOKEN'];

    // use the new instance to make your get request
    instance.get('https://api.instagram.com/v1/users/self/media/recent/?access_token=[MY_ACCESS_TOKEN]')
        .then(response => console.log(response))
}