首页 > 解决方案 > 我该如何解决:在预检响应中 Access-Control-Allow-Headers 不允许请求标头字段 x-access-token?

问题描述

我正在尝试从我的本地地址 (localhost:3000) 将图像上传到 Cloudinary。但是,当我尝试将图像上传到它时,它给了我这个错误: Access to XMLHttpRequest at 'https://api.cloudinary.com/v1_1/dz8xmxmly/image/upload' from origin 'http://localhost: 3000' 已被 CORS 策略阻止:在预检响应中 Access-Control-Allow-Headers 不允许请求标头字段 x-access-token。 这是我的代码 -

import React from "react";
import axios from "axios";
const Input = (props) => {
const uploadImage = (event) => {
const file = event.target.files[0];
const formData = new FormData();
formData.append("file", file);
formData.append("upload_preset", "lwop0fgy");
axios.post("https://api.cloudinary.com/v1_1/dz8xmxmly/image/upload", formData)
.then((response) => {
  console.log(response.data.url);
})}
return (
<>
<input  type="file" onChange = {uploadImage} />
</>
 );
 };
 export default Input;

标签: reactjsfile-uploadaxioscloudinary

解决方案


在编写我的第一个应用程序时,我遇到了同样的问题。CORS - 跨访问资源共享适用于您尝试从其他域获取/放入数据时。

预检请求 - 请求哪个浏览器在后端服务器上代表您检查您是否有资格/授权仅进行 CRUD 操作(用于放置、删除、发布)请求。

在后端Cloudinary仅允许具有某些标头的请求,而这些标头在您的发布请求中不存在,例如,Cloudinary不允许x-access-token您尝试发送的标头。

但我不确定您在 axios 中究竟从哪里设置标题。

您可以将代码更改为以下


    axios.post("https://api.cloudinary.com/v1_1/dz8xmxmly/image/upload",formdata,{
    headers:{
       //read cloudinary documentation and write approproate headers here 
    }
    })
    .then((res)=>{
       //do something
    })
    .catch((err)=>{
      //do somehting
    })

请参阅此帖子以获取更多信息。


推荐阅读