首页 > 解决方案 > 如何在本机反应中发送 axios 请求?

问题描述

我是 React Native 的新手,我正在尝试将 axios 请求发送到我的后端,但我陷入了困境。

export const login = (email, password) => async dispatch => {
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    };
    
    const body = JSON.stringify({ email, password });
    
        const res = await axios.post(`http://localhost:8000/auth/jwt/create/`, body, config);
        console.log('kk');
        dispatch({
            type: LOGIN_SUCCESS,
            payload: res.data
        });

        dispatch(load_user());
    
};

当它尝试通过 axios 发布请求时,会出现以下错误。错误

虽然我已经在 React JS 中尝试过这个并且它运行良好。请帮助我在本机反应中解决这个问题

标签: react-nativeaxios

解决方案


根据React Native Networking Docs,React Native 支持fetchWeb API来发送请求。我建议您使用fetch,而不是axios因为它具有所有相同的功能而没有任何额外的膨胀和开销。这是您要使用的代码的一个端口fetch

export const login = (email, password) => async (dispatch) => {
   const res = await fetch(`http://localhost:8000/auth/jwt/create/`, {
      method: "POST", // this signnifies POST request type
      body: JSON.stringify({ email, password }), // still including the body
      headers: {
         // apply the headers
         "Content-Type": "application/json"
      }
   });

   const data = await res.json(); // parses the body as a json object

   console.log("kk");

   dispatch({
      type: LOGIN_SUCCESS,
      payload: data
   });

   dispatch(load_user());
};


推荐阅读