Imgur api请求被CORS政策阻止

问题描述 投票:0回答:1

我想在ReactJS中创建一个组件,以便能够使用他们的api向imgur上传图片。

为了达到这个目标,我使用了AntDesign的Upload组件,并设置了一个函数作为action,让axios向imgur的api发出请求。

<Upload
  action={file => {
    const data = new FormData();
    data.append('image', file);
    const config = {
      headers: {
        'Content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Client-ID xxxxxxxx'
      }
    }

    return axios.post('https://api.imgur.com/3/upload', config, data)
  }}
  listType="picture-card"
  fileList={fileList}
  onPreview={this.handlePreview}
  onChange={this.handleChange}
>
  {fileList.length >= 1 ? null : uploadButton}
</Upload>

但当我尝试上传任何文件时,我得到的只有这个结果。

Access to XMLHttpRequest at 'https://api.imgur.com/3/upload' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

还有一个明显的由于请求阻塞而导致的未捕获的承诺。

Uncaught (in promise) Error: Network Error
    at createError (createError.js:17)
    at XMLHttpRequest.handleError (xhr.js:87)

可能是我的代码出了问题,因为在postman上做同样的请求有一个成功的结果,但我找不到问题所在。

编辑:你是对的,postman不受CORS的限制。

javascript reactjs axios antd imgur
1个回答
0
投票

将此添加到你的头像上------------------------------------------。

headers: {
  'Authorization': 'Client-ID ' + 'YOUR_CLIENT_ID', 
  'Cache-Control': null, // this is what will match the response headers
  'X-Requested-With': null
}
© www.soinside.com 2019 - 2024. All rights reserved.