1

I've been working on a project using Traccar API and React.

My problem is that I want to save the value of set-cookie response Header, to store it in the browser's cookies.

I want to do this because, neither Firefox or Chrome set the cookie on the browser.

Cookie not set

But on both browsers I get the same response Header.

Response header

This is my function, and as you can see, I tried to get the value of set-cookie using response.headers.get()

    const login = async () => {

        setLoading(true);
        const myHeaders = new Headers();

        myHeaders.append("Authorization", "Basic Og==");
        myHeaders.append("Content-Type", "application/x-www-form-urlencoded");


        var urlencoded = new URLSearchParams();
        urlencoded.append("email", user.email);
        urlencoded.append("password", user.password);

        var requestOptions = {
            method: 'POST',
            headers: myHeaders,
            body: urlencoded,
            credentials: 'include',
            redirect: 'manual',
        }

        trackPromise(
            fetch("http://x.x.x.x:7082/api/session", requestOptions)
                .then((response) => {
                    if (response.ok) {
                        console.log('Cookie: '+response.headers.get('set-cookie'))
                        redirect();
                    } else {
                        alert('There was a problem');
                    }
                })
                .catch(error => console.log('error', error))
        );
    }

But everytime I call the request, the result is the same.

Null value

Also, i tried to modify the credentials Header and using credentials: include,credentials: same-origin and credentials: omit, but still no luck.

I've been stuck with this problem for over a week, One of the things that I have noticed is that when testing the API methods in Postman, the JSESSIONID value, which come from set-cookie, is always used, this value is returned as a Response Header, but in the Code Snippets, is also set as a Request Header, that makes sense because every method on the API using Postman uses it as a Request Header.

So, how to get this value?

4

1 回答 1

1

类似的获取:从获取响应中获取 cookie

检查您可以阅读哪些标题:

fetch(URL, { credentials: 'include' })
 .then((response) => {
  
  for(let entry of response.headers.entries()) {
    console.log('header', entry);
  }
});

如果 cookie 已设置,请尝试以document.cookies. (它不适用于标记为 httpOnly 的 cookie)

于 2021-02-25T22:53:00.793 回答