반응형
Axios 인터셉터 - vuex 스토어에서 응답을 반환하는 방법
나는 로그인 양식을 가지고 있다.사용자가 사용자 이름/pw를 입력하면 api의 응답이 좋든 나쁘든 간에 api의 응답을 사용자가 처리한다.
그런 다음 응답은 사용자 자격 증명이 설정된 내 vuex 저장소를 통해 라우팅된다.
그러나 console.log에 응답을 로그인 구성 요소에 기록하면 다음과 같은 필드가 실제로 표시되지 않음data, status, headers등등.. 나는 이것을 본다.
사용자 로그인을 진행하기 전에 데이터가 저장소에 있는지 확인할 수 있는 방법이 있는가?
지금 이 시점에서 생각할 수 있는 것은 오직 a를 사용하는 것뿐이다.setTimeout3초간 주정부 getter에게 전화를 걸어 사용자 데이터를 검색한다.내 말은, 효과가 있지만 나는 더 적절한 해결책이 있다고 확신한다.
로그인.vue
onClickLogin() {
const userToLogin = {
username: this.loginForm.username,
password: this.loginForm.password
};
const response = UsersModule.login(userToLogin);
console.log("response", response); // returns what is pictured in the image above so the if block is technically wrong
if (response) {
this.$router.push("/");
}
}
axios 요청 클래스
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_URL,
timeout: 5000
});
service.interceptors.response.use(
response => {
return response.data;
},
error => {
Message({
message: error.message || "Error",
type: "error",
duration: 5 * 1000
});
return Promise.reject(error);
}
);
vuex 사용자 로그인 기능
@Action({ rawError: true })
async login(usersSubmit: UserSubmit) {
const response: any = await loginUser(usersSubmit);
if (typeof response !== "undefined") {
const { accessToken, username, name } = response;
setToken(accessToken);
this.SET_TOKEN(accessToken);
this.SET_USERNAME(username);
this.SET_NAME(name);
}
}
vuex 스토어에서 axios 요청을 호출하는 api 클래스
export const loginUser = (data: UserSubmit) => {
return request({
url: "/auth/login",
method: "post",
data
});
};
login이다async기능, 이것은 질문이 설명하는 것처럼 약속을 반환한다는 것을 의미한다.
비동기적 통제 흐름과 특히 약속은 전염성이 있기 때문에 이에 의존하는 모든 발신자도 약속을 사용해야 한다.에 유의하십시오.login응답으로 해결할 수 없도록 아무것도 반환하지 않음:
async onClickLogin() {
const userToLogin = {
username: this.loginForm.username,
password: this.loginForm.password
};
try {
await UsersModule.login(userToLogin);
this.$router.push("/");
} catch (err) {
console.error('Login failed');
}
}
반응형
'programing' 카테고리의 다른 글
| C 및 C++에서 유니언의 목적 (0) | 2022.04.25 |
|---|---|
| v-select 또는 v-comobox에서 "모두 선택" 옵션을 사용하는 방법 (0) | 2022.04.25 |
| Java에서 null 문자열을 연결 중 (0) | 2022.04.25 |
| JAXB를 사용하여 XML 문자열에서 개체 생성 (0) | 2022.04.25 |
| Vue js 어레이로 문자열을 분할하고 목록 렌더러에서 사용하는 방법 (0) | 2022.04.25 |
