简体   繁体   中英

Loading Data from Behance API in React Component

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM