Reputation: 45
I am currently trying to post to cloudinary via client side and I am getting the following error:
Access to XMLHttpRequest at 'https://api.cloudinary.com/v1_1/dd5gloppf/add/image/upload' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I am basically trying to post to cloudinary and get back the url of the image I am posting to the api so i can eventually send it to my server and store it on my back end. does anyone know what i am currently doing wrong?
I am unsure of how to deal with a CORS policy error from the client-side. My code is as follows:
import React, { useState, useEffect } from 'react'
import axios from 'axios'
function App() {
const [image, setImage] = useState('')
const [loading, setLoading] = useState(false)
const url = 'https://api.cloudinary.com/v1_1/dd5gloppf/add/image/upload'
const preset = 'ml_default'
const onChange = e => {
setImage(e.target.files[0])
}
const onSubmit = async () => {
console.log('im running')
const formData = new FormData()
formData.append('file', image)
formData.append('upload_preset', preset)
try {
setLoading(true)
const res = await axios.post(url, formData, {
'Access-Control-Allow-Origin': '*'
})
console.log(res)
const imageUrl = res.data.secure_url
console.log(imageUrl)
} catch (err) {
console.error(err)
}
}
return (
<>
<div className='file-field input-field'>
<div className='btn'>
<span>Browse</span>
<input type='file' name='image' onChange={onChange} />
</div>
<div className='file-path-wrapper'>
<input className='file-path validate' type='text' />
</div>
<button onClick={onSubmit} className='btn center'>
upload
</button>
</div>
</>
)
}
export default App
Upvotes: 4
Views: 2442
Reputation: 1041
Uploading to Cloudinary is definitely possible to do from the client. As the developer behind Cloudinary's Upload Widget I can assure you that :)
However, if you'd like a "signed" upload. Meaning a secure way to ensure only "authorized" code can upload to your Cloudinary account, you do need a server component as explained here and here.
However, for demo/dev purposes, you can very easily upload to Cloudinary from the browser.
Check out this sandbox.
*** EDIT
To enable unsigned uploads, youd need to change your cloud settings (settings -> Upload -> Upload presets).
You will then have an unsigned upload preset, its name will be the string you use in the code
Upvotes: 1