iphonic
iphonic

Reputation: 12717

Unable to make LinkedIn API calls from localhost with Axios

I am trying to access linkedin profile using axios get request, which doesn't work on localhost and I get the following error

XMLHttpRequest cannot load https://api.linkedin.com/v1/people/~:(id,email-address)?format=json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8030' is therefore not allowed access. The response had HTTP status code 401.

I am able to get access-token using react-linkedin-login package, after getting the access token I am trying the following code

var linkedInUrl = `https://api.linkedin.com/v1/people/~:(id,email-address)?format=json`;
  var headers = {
    'Authorization': `Bearer ${accessToken}`,
    'Access-Control-Allow-Methods':'GET,PUT,PATCH,POST,DELETE',
    'Access-Control-Allow-Origin':'*',
    'Access-Control-Request-Headers':'Origin, X-Requested-With, Content-Type, Accept',
    'Content-Type':'application/x-www-form-urlencoded'
  };

  return (dispatch) => {
    axios.get(linkedInUrl, {headers}).then(({data}) => {
        console.log(data);
    }, (error) => {
        console.log(error);
    });
  }

The problems lies in linkedin server how it takes request I guess, it doesn't allow localhost to make call I think. How to overcome this to actually develop the service before I deploy and run on server.

Thanks for helping..

Upvotes: 1

Views: 3734

Answers (3)

BennKingy
BennKingy

Reputation: 1593

https://cors-anywhere.herokuapp.com/ - Add this before the url and it will work

Upvotes: 1

Joel Raju
Joel Raju

Reputation: 1360

try jsonp for CORS request - reference - axios cookbook

var jsonp = require('jsonp');
jsonp(linkedInUrl, null, function (err, data) {
  if (err) {
    console.error(err.message);
  } else {
    console.log(data);
  }
});

EDIT

Use jQuery to perform JSONP request and to set headers

$.ajax({url: linkedInUrl,
  type: 'GET',
  contentType: "application/json",
  headers: header, /* pass your header object */
  dataType: 'jsonp',
  success: function(data) {
    console.log(data);
  },
  error: function(err) {
    console.log('Error', err);
  },
});

Upvotes: 1

Duncan Thacker
Duncan Thacker

Reputation: 5188

This is because of a browser restriction called the "Same-origin Policy", which prevents fetching data from, or posting data to, URLs that are part of other domains. You can get around it if the other domain supports Cross-origin Resource Sharing (CORS), but it looks like LinkedIn doesn't, so you may have trouble.

One way around this is to have a web service which can proxy your request to LinkedIn - there's no domain restrictions there.

https://en.wikipedia.org/wiki/Same-origin_policy

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Upvotes: 1

Related Questions