Vue3 跨域請求攜帶cookie操作並記錄cookie

Roc Huang發表於2020-10-28

近期做的專案比較雜,涉及到前端框架的工作,遇到了許多問題,記錄一下這個比較棘手的問題;
專案已有基礎:
已解決跨域訪問的問題,確保請求不會被遮蔽,vue專案中已經配置好了axios

axios.post('/users/', {
                        username: this.username,
                        password: this.password,
                    }, {
                        responseType: 'json',
                        withCredentials: true
                    })
                    .then(response => {
                         // 記錄使用者的登入狀態
                        sessionStorage.clear();
                        localStorage.clear();

                        localStorage.token = response.data.token;
                        localStorage.username = response.data.username;
                        localStorage.user_id = response.data.id;

                        location.href = '/index.html';
                    })
                    .catch(error=> {
                        if (error.response.status == 400) {
                            if ('non_field_errors' in error.response.data) {
                                this.error_sms_code_message = error.response.data.non_field_errors[0];
                            } else {
                                this.error_sms_code_message = '資料有誤';
                            }
                            this.error_sms_code = true;
                        } else {
                            console.log(error.response.data);
                        }
                    })

相關文章