【问题标题】:How to send axios reques in react native?如何在本机反应中发送axios请求?
【发布时间】:2021-09-04 15:09:10
【问题描述】:

我是 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 native 中解决这个问题

【问题讨论】:

    标签: react-native axios


    【解决方案1】:

    根据React Native Networking Docs,React Native 支持fetch web 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());
    };
    
    

    【讨论】:

    • @Ruma 然后在请求代码周围添加一个try-catch,然后注销错误。
    • 我试过了,在这种情况下,catch 块正在运行。甚至在 console.log() 行之前
    • @Ruma 是的,这意味着您的请求失败了。你设置 CORS 了吗?
    • 是的,我已经设置了核心,并且在 react js 项目中这些都运行良好
    【解决方案2】:

    尝试这样使用:

    // define axios request
    
    import axios from 'axios';
    
    const request = axios.create({
      baseURL: 'https://url.com/api/v1',
      timeout: 20000,
    });
    
    request.interceptors.request.use(
      config => {
        // config.headers.Authorization = `Bearer ${token}`;
        config.headers.Accept = 'Application/json';
        return config;
      },
      error => {
        //return Promise.reject(error);
        console.log("interceptors.request: ", error);
        return false;
      },
    );
    
    request.interceptors.response.use(
      response => {
        if (response && response.data) {
          return response.data;
        }
    
        return response;
      },
      error => {
        console.log('Response error: ', error);
        //throw error;
        return false;
      },
    );
    
    export default request;
    
    

    用法:

    import request from '../';
    
    export const getAPI = () => {
      return request({
        url: '/getData',
        method: 'GET',
        // ...
      });
    };
    
    getAPI().then(response => {
      //...
    });
    

    【讨论】:

    • 你能解释一下吗?在哪里编写此代码以及如何在我的代码中使用它
    猜你喜欢
    • 2021-07-01
    • 2022-01-18
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2019-10-30
    • 1970-01-01
    相关资源
    最近更新 更多