0

"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

1
  • Access-Control-Allow-* headers do not belong in requests. You can safely drop them.
    – jub0bs
    Mar 15 at 16:58

2 Answers 2

0

Cors always messes me up as well, I feel like I only deal with it every once in a while, so never enough to remember how I fixed it last time.

in this case though, I believe it's coming from the redirect in the back end, I think it's better if you returned the id to the front-end and then navigated to the url in the front-end

I would just have the backend handle the saving and return the id like this

router.post('/', validateCampground, catchAsync(async (req, res, next) => {
    const newCampground = new Campground(req.body.campground);
    await newCampground.save();
    res.json({ newCampgroundId: newCampground._id });
}));

then I would try something like this to redirect your page

const handleSubmit = (e) => {
    e.preventDefault();

    instance.post(
        `${BASE_URL}/campgrounds`,
        inputInfo,
        {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => {
            window.location.href = `/campgrounds/${response.data.newCampgroundId}`;
        })
        .catch(error => {
            console.error("Error: ", error);
        });
}
0

request url on your frontend and backend must match to each other. On backend: router.post('/campgrounds', validateCampground, catchAsync(async (req, res, next) => { // doing something }

this should work Your router.post() should catch a same url you send from client, if is is, then your code in that router.post will be executed and then enables the CORS policy as you wish, otherwise, it won't run. You might want to delete your header{} in your request on client, because you cannot enable CORS on client side, so in this situation, it should not be there.

1
  • the urls match... in the backend its like just '/' but is a shortcut of the approach of use express.router to destructure. Im sure the urls match because like i said before.. the newCampground is getting saved ! but the problem is when i try to redirect Mar 15 at 17:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.