2017-12-25 2 views
1

Redux 형식을 사용하여 익스프레스 엔드 포인트로 POST 호출을 전송합니다. 엔드 포인트는 성공적으로 저장된 오브젝트 또는 오류를 리턴해야합니다.Axios-Redux가 익스프레스 엔드 포인트에 반응 함 - 둘 다 .then 및 .catch가 트리거 됨

끝점은 게시 된 데이터를 성공적으로 저장하고 JSON을 반환합니다. 그러나 돌아 오는 활동에 Axios의 모두 그 때는를 집어 들고 .catch 트리거-에 다음 액션, 다음과 같은 로그 : 내가 잘못

successful response: { …} 
failure response: undefined 

을 뭐하는 거지?

내 Axios의 액션 :

export function addPlot(props) { 
    const user = JSON.parse(localStorage.getItem('user')); 
    return function(dispatch) { 
     axios 
      .post(
       `${ROOT_URL}/plots`, 
       { 
        props 
       }, 
       { headers: { authorization: user.token } } 
      ) 
      .then(response => { 
       console.log('successful response: ', response.data); 
       const plotModal = document.getElementById('plotModal'); 
       plotModal.modal('dispose'); 
       dispatch({ type: PLOT_ADDED, payload: response.data }); 
       dispatch({ type: ADDING_PLOT, payload: false }); 
       dispatch({ 
        type: NEW_PLOT_GEOJSON, 
        payload: '' 
       }); 
      }) 
      .catch(response => { 
       console.log('failure response: ', response.data); 
       dispatch(authError(PLOT_ADD_FAILURE, 'Failed to add plot')); 
      }); 
    } 

의 엔드 포인트 :

exports.newPlot = async (req, res, next) => { 
    console.log(JSON.stringify(req.body.props)); 
    let company; 
    if (req.user.companyCode !== 'Trellis') { 
     company = req.user.companyCode; 
    } else { 
     company = req.body.props.company; 
    } 
    const { 
     name, 
     feature, 
     growerPhone, 
     plotCode, 
     rootStock, 
     region, 
     variety, 
     grower, 
     planted 
    } = req.body.props; 
    const plot = new Plot({ 
     name, 
     grower, 
     variety, 
     planted, 
     region, 
     rootStock, 
     plotCode, 
     growerPhone, 
     feature, 
     company 
    }); 
    try { 
     const newPlot = await plot.save(); 
     res.json(newPlot); 
    } catch (e) { 
     console.log("couldn't save new plot", JSON.stringify(e)); 
     return res.status(422).send({ error: { message: e, resend: true } }); 
    } 
}; 

답변

1

당신은 비동기 작업을 관리 할 수 ​​redux-thunk 미들웨어를 사용할 수 있습니다.

내가보기에 문제는 axios 동작을 전달하지 않는다는 것입니다. redux 저장소에서 무언가를 수행하려면 dispatch(this.props.addPlot(props))으로 전화해야합니다.

+0

죄송합니다. 무엇을 의미합니까? –

+0

당신은 액션 (또는 썽크)'addPlot'을 보내지 않았습니다. 호출의 순간에, 당신의 반응 컴포넌트에서, 당신은'this.props.dispatch'로 포장해야합니다. 희망이 작동합니다. –

관련 문제