Home > database >  Why cookies do not stored when set it with axios POST method
Why cookies do not stored when set it with axios POST method

Time:09-07

I'm trying to write and read cookies and falling into a problem below.

This is my basic server side:

server.js

const app = express();
app.use(cors());
app.use(cookieParser());

import routes from '...';
app.use("/foo", routes);

app.listen(8888);

routes.js

const routes = express.Router();
routes.post('/', (req, res) => {
    res.cookie("myFoo", "abcd");
    res.send("Cookie added");
    }
});

routes.get('/', (req, res) => {
    res.send(req.cookies.myFoo);
    }
});
export default routes;

And my client side at "http://localhost:3000".

I do two HTTP request

POST http://localhost:8888/foo
GET http://localhost:8888/foo

And get the response exactly what I expected abcd. Also, the cookie exists in the browser tab Application > Cookies too.

The problem cases when axios is used in the client.

const api = axios.create({
    baseURL: "http://localhost:8888/foo"
});

async function setCookie(object) {
    return api.post("/", object)
    .then((res) => {
        return res;
    });
}

function getCookie() {
    return api.get("/")
    .then((res) => {
        return res;
    });
}

setCookie({})
.then((res) => {
    getCookie();
})

The api.post() run usually and the header response Set-Cookie is correct. But cookies in the browser tab Application > Cookies are empty. Also, api.get() get the undefined.

I did try to move res.cookie() or the set cookie job in server side to GET route it WORKS on both HTTP and axios

routes.get('/', (req, res) => {
    res.cookie("myFoo", "abcd");
});

tldr: Set cookie in HTTP POST method work fine but when client use axios to call so it causes problems.

Can you show me why this happened? And which code part went wrong that caused me into this?

CodePudding user response:

Cookies are only used in cross-origin Ajax requests when:

  • The client asks to use them
  • The server grants permission to use them cross origin

So you need to change the client side code to ask for them:

const api = axios.create({
    baseURL: 'http://localhost:8888/',
    withCredentials: true,
});

And the server code to grant permission (note that you can't use credentials at the same time as the wildcard for origins).

app.use(cors({ 
    origin: 'http://localhost:3000', 
    credentials: true 
}));
  • Related