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

1👍

Your AJAX request to the Instagram API endpoint has to be sent as a jsonp request which means the dataType of the request has to be jsonp.

This blob in axios repository contains an example of sending a request using jsonp which is mentioned below.

Install jsonp package, if you haven’t already.

npm install jsonp --save

and then;

const jsonp = require('jsonp');

jsonp('http://www.example.com/foo', null, (err, data) => {
  if (err) {
    console.error(err.message);
  } else {
    console.log(data);
  }
});

Below is an example of sending a request using jQuery method with jsonp dataType to the Instagram API endpoint.

$.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);
    }
});
👤Kazmi

2👍

Laravel automatically applies the X-CSRF-TOKEN header to all axios requests. This is so you can communicate with your application without having to pass the CSRF token every time for POST, PUT, DELETE, etc.

resources/js/bootstrap.js (default settings)

/**
 * 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');
}

You should be able to remove the offending header by doing something like this:

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))
}


Leave a comment