Home > other >  How to locally test set Cookies with the Same Origine Policy
How to locally test set Cookies with the Same Origine Policy

Time:12-14

I have a problem when testing my web app locally. I set cookies in a request response (here is how) :

const token = createToken(user._id);
res.cookie("jwt", token, { httpOnly: true, maxAge: maxAge,  });
res.status(201).json({ user: user._id });
return res;

But I encounter an error about Same domain Policy when executing the following request in the React Client:

axios.post(`${process.env.REACT_APP_API_URL}api/user/login`, {
                email: email,
                password: password,
            },
            {
                withCredentials: true
            })
            .then((res) => {
                if (res.data.errors) {
                    //Show errors
                }
            })
            .catch((err) => {
                console.log(err);
            }); 

I tried to execute it with the parameter withCredentials : false

The request works but the cookie is not stored But I have set-Cookie in the response of my request

And this is my CORS options :

const corsOptions = {
    origin: process.env.CLIENT_URL,
    credentials: true,
    allowedHeaders: ["sessionId", "Content-Type"],
    exposedHeaders: ["sessionId"],
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    preflightContinue: false
};

CodePudding user response:

I remplace my cors options by :

const corsOptions = {origin: process.env.CLIENT_URL,credentials: true};

and add :

app.options('*', cors(corsOptions));

and now it's working

  • Related