在 React 组件中从 Behance API 加载数据 [英] Loading Data from Behance API in React Component

查看:25
本文介绍了在 React 组件中从 Behance API 加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过他们的 API 加载 Behance 项目数据.无论是本地主机还是 prod,我都收到以下错误 --

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

Fetch API 无法加载 XXX.对预检请求的响应未通过访问控制检查:请求的资源上不存在Access-Control-Allow-Origin"标头.Origin 'http://localhost:5000' 因此不允许访问.如果不透明响应满足您的需求,请将请求的模式设置为no-cors"以在禁用 CORS 的情况下获取资源.

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.

不知道如何解决这个问题.我在下面 Portfolio 组件中的代码 --

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

}

更新:使用 jQuery ajax 代替 fetch.--

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

推荐答案

这似乎对 React 影响不大,而对 Behance 影响更大.您得到的是 CORS 错误,正如您可能认为的出去.简短的解释是,CORS 是一种置于浏览器中的安全措施,因此网站无法从浏览器请求其他网站以显示为第二个网站.这是一种安全措施,可防止某些网络钓鱼攻击.

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(在本例中为 Behance),但出于正当理由,他们决定不禁用.

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

Behance 可能会允许您改为从服务器发出您尝试发出的请求.完成此操作后,您需要将信息从服务器获取到 React 应用程序,然后一切顺利!

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!

这篇关于在 React 组件中从 Behance API 加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆