"Access to XMLHttpRequest at 'http://localhost:3000/campgrounds/6411f03e718f68104cac045a' (redirected from 'http://localhost:5000/campgrounds') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
This is my code on the front-end side of my app
const instance = axios.create(
{
baseURL: '',
withCredentials: false,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS'
}
})
const handleSubmit = (e) => {
e.preventDefault()
instance.post(
`${BASE_URL}/campgrounds`,
inputInfo,
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
}
And this is my code from the back-end side of my app
router.post('/', validateCampground, catchAsync(async (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
const newCampground = new Campground(req.body.campground)
await newCampground.save()
res.redirect(`${BASE_URL}/campgrounds/${newCampground._id}`)
}))
but im receiving this error when i tried tor redirect(because the campground get saved in the db) at the end of the endpoint logic : "Access to XMLHttpRequest at 'http://localhost:3000/campgrounds/6411f03e718f68104cac045a' (redirected from 'http://localhost:5000/campgrounds') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
Also, at the top of my backend im using the cors(()) package like this :
const corsOptions ={
origin:'*',
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200
}
app.use(cors(corsOptions));
I didnt know what im doing wrong... im tired of trying figured out .. i research a lot, i asked to chatgpt xd and i cant fix this issue.
PD : after handling the form with a onSubmit logic (controlled component), i was using the un-controlled approach sending my form data across the action/method props and having no issue, but when i change the approach like i showed after.... that f***** error.
please help me
just in case this is the repo > https://github.com/JulianOviedo/YelpCamp
Access-Control-Allow-*
headers do not belong in requests. You can safely drop them.