'How can I fix : Request header field x-access-token is not allowed by Access-Control-Allow-Headers in preflight response?
I am trying to upload an image to Cloudinary from my local address (localhost:3000). However, when I try upload an image to it, it is giving me this error: Access to XMLHttpRequest at 'https://api.cloudinary.com/v1_1/dz8xmxmly/image/upload' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field x-access-token is not allowed by Access-Control-Allow-Headers in preflight response. Here is my code -
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;
Solution 1:[1]
I faced same issues while writing my first application. CORS - Cross Access Resource Sharing Applicable when you try to fetch/put data from other domains.
Preflight request - request which browser makes behalf of you at the backend server to check whether you are elligible/authorized to make CRUD operations (for put,delete,post) requests only.
At backend Cloudinary
has allowed only requests with certain headers which are not there in your post request
eg, Cloudinary
does not allow x-access-token
which you are trying to send.
But I am not sure from where exactly you are setting up headers in axios.
You might change your code to the following
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
})
Please refer to this post for additional information.
Solution 2:[2]
const formData = new FormData();
formData.append("file", files[0]);
formData.append("upload_preset", "sdfsfuyi");
const instance = axios.create();
instance.post("https://api.cloudinary.com/
v1_1/cloud_name/image/upload", formData)
Note the const instance = axios.create();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Makarand |
Solution 2 | Andrew |