reactjs - 我该如何解决:在预检响应中 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;
解决方案
在编写我的第一个应用程序时,我遇到了同样的问题。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
})
请参阅此帖子以获取更多信息。
推荐阅读
- c# - 在 JSON 反序列化中跳过空数组
- android-10.0 - 如何在 Android Q 中创建后台系统服务
- python - 什么是通过第三个列表的索引将列表的值添加到另一个列表的值并输出前两个列表之一的方法?
- python - 合并两个数据框的更有效方法
- r - 使用 3 个不同的数据输出第 4 个数据帧
- python - 获取 matplotlib 图形轴类型
- ios - 适用于 iOS 的 Google Analytics(分析)SDK 是否具有 SSL 固定?
- python - 如何使用用户定义的函数执行 groupy by?
- python - 如何将预训练的 tensorflow pb 冻结图转换为可修改的 h5 keras 模型?
- python - 用于批量转换的 AWS SageMaker 部署