【问题标题】:Fetch request to Cloudinary API from with React Component fails从 React 组件获取对 Cloudinary API 的请求失败
【发布时间】:2018-12-04 06:46:09
【问题描述】:

我想向 Cloudinary API 发出 HTTP 请求以获取我帐户中的图片。必要的 url 如下所示:

https://<<API KEY>>:<<API SECRET>>@api.cloudinary.com/v1_1/<<RESOURCE NAME>>/resources/image

当我从浏览器中点击这个 url 时,我得到了我正在寻找的东西,一个带有我所有图片的漂亮 JSON 对象。

但是当我从 React 组件中点击 url 时,

componentDidMount() {
  this.props.fetchArt();
}

我收到以下错误:

TypeError: Failed to execute 'fetch' on 'Window': Request cannot be constructed from a URL that includes credentials:

动作创建者的样子

export function fetchArt() {
  const url = 'https://'+CLOUDINARY_KEY+':'+CLOUDINARY_SECRET+'@api.cloudinary.com/v1_1/prints20/resources/image';
  const request = fetch(url).then(res => res.json())
  return {
    type: FETCH_ART,
    payload: request
  }
}

回购链接:https://github.com/PantherHawk/prints20-2018

提前一百万谢谢!

【问题讨论】:

  • 如果这是一个 CLOUDINARY_SECRET,它应该是秘密的。不要把它放在你的前端代码中。您可能必须创建一个访问它的服务器。它还将解决您的 CORS 问题????

标签: reactjs http frontend cloudinary


【解决方案1】:

如果您的端点需要某种授权,您需要在请求的标头中传递该信息。 Cloudinary 身份验证是使用基于安全 HTTP 的基本身份验证完成的。您的 Cloudinary API Key 和 API Secret 用于身份验证。

fetch('https://api.cloudinary.com/v1_1/CLOUD_NAME/resources/image', {
  method: 'get',
  headers: {
    'Authorization': 'Basic ' + base64.encode(API_KEY + ":" + API_SECRET),
  },
}).then(res => res.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:8080' is therefore not allowed access. The response had HTTP status code 404.还有其他提示吗?
  • 我应该在我的后端服务器中编写这个获取请求吗?因为从我的 componentDidMount 函数运行它时,我仍然发现 CORS 问题。谢谢。
  • CORS 是另一个问题,这个问题在云端而不是在您的代码中。我认为 cloudinary 不允许来源 localhost:8080。尝试将您的站点部署在服务器上或出于安全考虑,将其放入您的后端。
  • 获取请求只在浏览器中可用,如果你的后端使用node js,你可以使用这个库https://github.com/bitinn/node-fetch
猜你喜欢
  • 2019-07-09
  • 2021-04-25
  • 2015-04-03
  • 2018-05-21
  • 2022-11-06
  • 2017-02-10
  • 1970-01-01
  • 2016-03-02
  • 2020-04-25
相关资源
最近更新 更多