2

I need to set up a cookie in browser after sending a POST request in a javascript(js) and try to ask the browser to send this new-set cookie back in a subsequent fetch GET request.

Here is my js script:

fetch(authorise_url, {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    credentials: 'include',
    body: JSON.stringify({
        "code": code
    })
}).then((response) => {
    const url_test = 'http://localhost:8888/test-cookie/';
    return fetch(url_test, {credentials: 'include'})
        .then((response) => {
            console.log(response.text());
        }).then((error) => {
            console.log(error);
        })
});

Server side code in authorise_url: response.set_cookie('test_cookie', 'test_cookie_value', httponly=True)

Server side code in test-cookie: print(str(request.COOKIES))

I read Fetch API with Cookie and used credentials: 'include' in my JS requests. Cookie is set up in browser but the cookie is not sent but my subsequent GET request.

I tested sending two GET requests, the cookie can be set up and sent by send GET fetch request using the following code.

function getCookie() {
    fetch(authorise_url, {
        credentials: 'include'
    }).then((response) => {
        console.log(response.text());
        const url_test = 'http://localhost:8888/test-cookie/';
        return fetch(url_test, {credentials: 'include'})
            .then((response) => {
                console.log(response.text());
            }).then((error) => {
                console.log(error);
            })
    });
}

But I failed to get the cookie in the combination of POST and GET fetch request.

Is there some considerations when sending the GET request with cookie after a POST?

Jun Zhou
  • 1,077
  • 1
  • 6
  • 19

0 Answers0