programing

모든 요청에 대해 서버에서 Vue + Axios 처리 오류 발생

prostudy 2022. 6. 26. 09:32
반응형

모든 요청에 대해 서버에서 Vue + Axios 처리 오류 발생

Vue + Axios + Vue Router + Vuex 를 사용하고 있습니다.

Vue에서 인증을 처리하고 싶은데 로그인 후 사용자가 무엇이든 할 수 있습니다.단, 토큰이 만료되어 서버에서 오류가 발생할 수 있습니다.Code = 123내가 원하는 것은 서버가 나에게 정보를 준다면 로그인 페이지로 사용자를 리다이렉트하고 싶다는 것이다.Code = 123. 공리의 모든 응답은 확인할 수 있지만, 영향을 미치는 공리 요청이 수백 개 있기 때문에 효과적이지 않습니다.

질문:.

  1. 서버가 다음과 같은 오류 코드를 제공하는 경우 리디렉션 방법Code = 123이것은 수백 개의 악리 반응에서 발생합니다.

주의해 주십시오.

  1. 서버 측 검사, 서버가 토큰을 해지할 수 있으므로 프런트 엔드로 토큰 만료를 막을 수 없습니다.
  2. 나는 수백 개의 응답을 수동으로 체크하는 글을 쓰고 싶지 않다.한 곳에서 처리할 수 있으면 좋기 때문에 리팩터를 만들면 쉽게 할 수 있을 것 같습니다.

@the grass, 글로벌레벨로 악시스를 설정해, 애플리케이션내의 악시에 액세스 할 수 있습니다.

글로벌 설정에서는 request 및 response intercepts를 사용합니다.

응용 프로그램에서 발생하는 모든 요청은 이 요청 대행 수신기를 통과하며 응답은 응답 대행 수신기를 통과합니다.

응답 코드가 123인지 여부를 나타내는 논리가 응답 대행 수신기에 있는 경우 클라이언트 측에 저장된 액세스 토큰을 삭제하고 사용자를 로그인 페이지로 리디렉션합니다.

Axios 가로채기 샘플을 찾으십시오(vue js 응용 프로그램에서 Axios 글로벌 가로채기 설정에 대한 자세한 내용은 참조하십시오).

in axios-config.js 파일

import axios from 'axios';

const http = axios.create();

/* Response Interceptors */
const interceptResErrors = (err) => {
  try {
    // check for response code 123 and redirect to login
    err = Object.assign(new Error(), {message: err.response.data});
  } catch (e) {
    // check for response code 123 and redirect to login
    // Will return err if something goes wrong
  }
  return Promise.reject(err);
};
const interceptResponse = (res) => {
  try {
    // check for response code 123 and redirect to login
    return Promise.resolve(res.data);
  } catch (e) {
    // check for response code 123 and redirect to login
    return Promise.resolve(res);
  }
};
http.interceptors.response.use(interceptResponse, interceptResErrors);

/* Request Interceptors */
const interceptReqErrors = err => Promise.reject(err);
const interceptRequest = (config) => {
  return config;
};
http.interceptors.request.use(interceptRequest, interceptReqErrors);

export default http;

이 파일은 HTTP 클라이언트 Axios 개체를 내보냅니다. 이 개체를 아래와 같이 main.js/app.js의 Vue 인스턴스에 가져오거나 마운트할 수 있습니다.

import http from axios-config.http

Vue.protype.$api =http;

컴포넌트 내부

this.$api.get('/some-api');

언급URL : https://stackoverflow.com/questions/66850745/vue-axios-handling-error-from-server-for-all-request

반응형