【问题标题】:React doesn't set cookies but Postman does?React 不设置 cookie 但 Postman 设置?
【发布时间】:2022-07-27 19:51:06
【问题描述】:

我有一个允许用户登录的 Spring Boot 后端。

当我使用邮递员发送 json 有效负载以登录用户时,它会返回正确的响应以及 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

【问题讨论】:

  • 我认为 cookie 与 React 或 Axios 无关。当服务器发送“Set-Cookie”标头时,浏览器需要保存到自己。您是否查看过 DevTools (F12) -> 应用程序 -> Cookies?编辑:对不起,你发布了 cookie 页面,我没看到。

标签: reactjs spring cookies axios postman


【解决方案1】:

'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
    });

【讨论】:

    【解决方案2】:

    我有同样的问题,我也在标题之外使用withCredentials: true

    但是,Postman 仍然没有获得 Cookies 和 React App。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      相关资源
      最近更新 更多