IT이야기

컨트롤러에서 Axios 캐치 섹션으로 json 응답 읽기 - Laravel Vue Axios

cyworld 2022. 5. 10. 22:25
반응형

컨트롤러에서 Axios 캐치 섹션으로 json 응답 읽기 - Laravel Vue Axios

나는 Axios가 생성한 PUT를 통해 vue 뷰(Profile.vue)에서 전송한 정보를 캡처하는 방법을 가지고 있는데, 문제는 데이터가 업데이트될 때(UserController의 myProfile 메소드를 사용하여), 악시오스가 방법으로부터 json으로 반환의 정보를 캡처하고, 성공 메시지가 표시될 때 다음과 같다.n 오류, Axios는 오류 json 정보를 캡처하지 않고 다음을 주장한다.

Uncaught (in promise) TypeError: Cannot read property 'status' of undefined

나는 네가 악시오스의 캐치 섹션에서 내가 가지고 있는 정보를 가지고 있지 않은 변수들에 의해 나에게 우롱하고 있다는 것을 이해한다.

myProfile 코드(UserController)

$profile = User::find(Auth::user()->id);
$profile->firstname = $request->firstname;
$profile->lastname = $request->lastname;
$profile->gender = $request->gender;
$profile->description = $request->description;
if($profile->update())
{
    return response()->json([
            'status' => 'Muy bien!',
            'msg' => 'Datos actualizados correctamente.',
            'cod' => 201
    ]);
}
else{
        return response()->json([
            'status' => 'Ocurrio un error!',
            'msg' => 'Ocurrio un error al actualizar la información.',
            'cod' => 400
            ]);
}

프로파일의 Axios 섹션.부에를 하다

axios.put('/dashboard/profile', value)
        .then((response) => {
            let title = response.data.status;
            let body = response.data.msg;
            this.displayNotificationSuccess(title, body);
        })
        .catch((response) => {
            let title = response.data.status;
            let body = response.data.msg;
            this.displayNotificationError(title,body);
        })

앞에서 말했듯이 콘트롤러에서 성공이 있을 때 악시오스는 json이라는 메시지를 읽고 보여주지만, 오류가 있을 때는 그렇지 않다.

악시오스가 컨트롤러에서 오는 에로 json 메시지를 보여줄 수 없는 내가 어디에서 실패하는가?

라라벨 5.6, 부에즈 2와 악시오스를 사용했다.

에서catch콜백, 인수는 에러 객체가 아니라response이의를 제기하다다음을 시도해 보십시오.

axios.put('/dashboard/profile', value)
    .then((response) => {
        let title = response.data.status;
        let body = response.data.msg;
        this.displayNotificationSuccess(title, body);
    })
    .catch((error) => {
        let title = error.response.data.status;
        let body = error.response.data.msg;
        this.displayNotificationError(title,body);
    })

소스

첫째 - 당신은 당신의 백엔드에서 두번째 부분이 실제로 오류라고 정의해야 한다. 그렇지 않으면 공리는 그것을 성공적인 요청으로 볼 것이다.

다음 두 번째 인수로 오류 상태 코드를 입력하여response()->json(json, code)여기서 상태 코드 목록을 볼 수 있다.

예:

return response()->json([
    'status' => 'Ocurrio un error!',
    'msg' => 'Ocurrio un error al actualizar la información.',
    'cod' => 400
], 400);

둘째, 공리.catch()응답이 아닌 오류를 반환한다.응답을 받으려면 전화를 해야 한다.err.response그 위에

예:

.catch((response) => {
    let title = response.response.data.status;
    let body = response.response.data.msg;
    this.displayNotificationError(title,body);
})

참조URL: https://stackoverflow.com/questions/49836036/read-json-response-from-controller-to-axios-catch-section-laravel-vue-axios

반응형