React 不设置 cookie 但 Postman 设置?

React doesn't set cookies but Postman does?

我有一个 spring 允许用户登录的引导后端。

当我使用 postman 发送一个 json 有效载荷来登录用户时,它 returns 正确的响应带有一个 JSESSION 的 cookie。

Postman details with response and cookie

当我在 react (axios) 中发送负载时,我在任何地方都看不到 JSESSION 的 cookie,但响应仍然正常?

const API_URL = "http://localhost:8080/api/auth/";


login(uniqueId: string, password: string) {
    return axios.post(API_URL + "login", JSON.stringify({
            "uniqueId": uniqueId,
            "password": password
        }), 
        {
            headers: {
                'Content-Type': 'application/json',
                'withCredentials': 'true'
            }
        })
        .then(response => {
            console.log(response);
            return response;
        }).catch(error => {
            return error.response
    });
}

Chrome tab with response and no cookie

'withCredentials': 'true' 应该在 headers (Request Config documentstion)

之外

你的情况是:

const API_URL = "http://localhost:8080/api/auth/";


login(uniqueId: string, password: string) {
    return axios.post(API_URL + "login", JSON.stringify({
            "uniqueId": uniqueId,
            "password": password
        }), 
        {
            withCredentials: true,
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            console.log(response);
            return response;
        }).catch(error => {
            return error.response
    });
}

另一种解决方案是使用参数 withCredentials: true (creating axios instance).

创建实例 axios
const BASE_URL = "http://localhost:8080/api/";
const api = axios.create({
baseURL: BASE_URL,
withCredentials: true,
headers: {'Content-Type': 'application/json'}
});

然后你可以做:

 return api.post("/auth/login", JSON.stringify({
            "uniqueId": uniqueId,
            "password": password
        })) .then(response => {
            console.log(response);
            return response;
        }).catch(error => {
            return error.response
    });