我正在尝试使用axios执行发布请求,以将图像从我的前端React应用程序上传到云。我从下面的axios代码中得到这个错误:
http://localhost:3000已被CORS策略阻止:预检响应中的Access-Control-Allow-Headers不允许请求头字段x-access-token。
使用公理,不工作给我cors错误
await axios({
method: "POST",
url: "https://api.cloudinary.com/v1_1/******/image/upload/",
data: {
file: img,
upload_preset: "*****",
cloud_name: "****",
},
})
.then((res) => {
console.log("response");
console.log(res);
})
.catch((err) => console.log(err));
同时,当我使用相同的api请求使用fetch时,post请求可以工作并且不会给我错误。有人知道为什么以及如何使用axios调用api吗?
const data = new FormData();
data.append("file", img);
data.append("upload_preset", "*****");
data.append("cloud_name", "*****");
await fetch(
" https://api.cloudinary.com/v1_1/****/image/upload/",
{
method: "post",
body: data,
}
)
.then((resp) => resp.json())
.then((data) => {
setUrlArray((prevState) => [...prevState, data.url]);
})
.catch((err) => console.log(err));
额外信息:我的上传预设是未签名的。
在进行axios api调用后,也从控制台得到了这个
{
error: {
message: "Upload preset must be specified when using unsigned upload"
}
}
要创建一个等效于您的工作fetch()
的Axios请求,您需要
>
制作一个FormData
实例并将其设置为请求data
,因此您的内容类型为multipart/form-data
确保您没有使用带有不需要的默认标头的先前创建的Axios实例
如果在默认Axios实例上设置了自定义标头,例如
axios.defaults.headers.common["x-access-token"] = TOKEN
您可能需要在transformRequest
中覆盖/删除它们
为避免在默认Axios实例上定义任何拦截器,请为未拦截的请求创建一个新的单独实例
import axios from "axios" // import the default instance
// create a new instance without interceptors.
// you could also create this in its own module and import from there
const instance = axios.create()
const data = new FormData()
data.append("file", img);
data.append("upload_preset", "*****");
data.append("cloud_name", "*****");
const res = await instance.post(
"https://api.cloudinary.com/v1_1/******/image/upload/",
data
)
理想情况下,如果您的应用程序要自定义请求,您应该始终使用Axios实例(或多个实例)以避免乱搞默认值。