Loading Data from Behance API in React Component

2019-02-28 17:17发布

问题:

I am trying to load Behance project data via their API. Whether its localhost or prod, I am getting the following error --

Fetch API cannot load XXX. 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:5000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Not sure how to solve for this. My code in the Portfolio component below --

getPortfolio = () => {

const USER_ID = `XXX`,
      PROJECT_ID = `XXX`,
      API_KEY = `XXX`;

const BEHANCE_URL = `https://api.behance.net/v2/users/${USER_ID}/projects?client_id=${API_KEY}`;
console.log(BEHANCE_URL);

fetch(BEHANCE_URL, {
  method: 'get',
  dataType: 'jsonp',
  headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
  }
}).then((response) => {
  return response.json();
}).then((responseData) => {
  return responseData;
}).catch((err) => {
  return err;
});

}

UPDATE: Instead of fetch, using jQuery ajax works. --

$.ajax({
  url: BEHANCE_URL,
  type: "get",
  data: {projects: {}},
  dataType: "jsonp"
}).done((response) => {
  this.setState({
    portfolioData: response['projects']
  });
}).fail((error) => {
  console.log("Ajax request fails")
  console.log(error);
});

回答1:

This seems to have do less with React and more with Behance. What you are getting is a CORS error as you probably figured out. The short explanation is that CORS is a security measure put in on the browser so that websites cannot request other websites from the browser to appear to be the second website. It is a safety measure in place to protect from some phishing attacks.

CORS can be disabled by the server (in this case, Behance) but they decide not to, for legitimate reasons.

Behance would probably allow you to make the request you are trying to make from a server instead. Once you do that, you will need to get the information from your server to your React application, and you will be good to go!