programing

Axios 400 오류 요청 콜 대신에 호출합니다.

codeshow 2023. 8. 5. 11:06
반응형

Axios 400 오류 요청 콜 대신에 호출합니다.

다음과 같은 기능이 있습니다.

add(App, Params, Callback){
    var self = this;

    var Data = self.process_fields(Params)

    self.$http.post(
        paths.api + '/app/' + App.Permalink,
        new URLSearchParams(Data)
    ).then(function (error, response) {
        console.log("then");
        if (typeof (Callback) == "function") {
            Callback(true, response.data.data);
        }
    }).catch(function(error){
        console.log("catch");
        if(typeof error.response !== "undefined"){
            errors.render(error.response.data.error)
        }

        if (typeof (Callback) == "function") {
            Callback(false, null);
        }
    });
}

요청을 호출하고 400 오류를 수신하면 캐치 대신 다음을 호출합니다.

enter image description here

해결책을 찾았습니다.

axios 인터셉터에서 약속을 반환하지 않아 발생한 문제:

axios.interceptors.response.use((response) => {
    return response;
}, (error) => {
    if (!error.response) {
        alert('NETWORK ERROR')
    } else {
        const code = error.response.status
        const response = error.response.data
        const originalRequest = error.config;

        if (code === 401 && !originalRequest._retry) {
            originalRequest._retry = true

            auth.commit('logout');
            window.location.href = "/login";
        }

        return Promise.reject(error)
    }
});

추가return Promise.reject(error)아주 효과적인

이는 이전 버전의 Axios에서 의도한 것입니다.

validateStatusv0.11 이후 구성에 추가되었습니다.이 옵션을 사용하여 유효한 상태 코드 범위를 지정할 수 있습니다.기본적으로 유효한 코드는 >= 200 및 < 300입니다.

validateStatus: function (status) {
  return status >= 200 && status < 300; // default
},

참조: https://github.com/axios/axios/issues/41#issuecomment-215100137

다음과 같은 응답 가로채기 추가

axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

언급URL : https://stackoverflow.com/questions/47679543/axios-400-error-request-call-then-instead-of-catch

반응형