简体   繁体   English

从React组件中的Behance API加载数据

[英]Loading Data from Behance API in React Component

I am trying to load Behance project data via their API. 我正在尝试通过其API加载Behance项目数据。 Whether its localhost or prod, I am getting the following error -- 无论是本地主机还是产品,我都会收到以下错误-

Fetch API cannot load XXX. 提取API无法加载XXX。 Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 对预检请求的响应未通过访问控制检查:请求的资源上不存在“ Access-Control-Allow-Origin”标头。 Origin ' http://localhost:5000 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:5000 '。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。

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. 更新:使用jQuery ajax可以代替获取。 -- -

$.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. 这似乎对React没什么作用,而对Behance却有更多的作用。 What you are getting is a CORS error as you probably figured out. 您可能会发现,您得到的是CORS错误 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. 简短的解释是,CORS是一种在浏览器中使用的安全措施,因此网站无法从浏览器请求其他网站显示为第二个网站。 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. 服务器可以禁用CORS(在本例中为Behance),但出于正当理由,他们决定不这样做。

Behance would probably allow you to make the request you are trying to make from a server instead. Behance可能会允许您改为尝试从服务器发出请求。 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! 完成后,您需要将信息从服务器发送到React应用程序,您将一路顺风!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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