如何在react native中使用axios post,在postman中使用时有效,但在react-native中使用时不起作用

时间:2019-08-17 18:41:03

标签: react-native axios expo

以下代码是从邮递员代码段生成的,任何人都可以将其转换为可用于react-native的axios:

var request = require("request");

var options = { method: 'POST',
  url: 'http://myurl.com',
  headers: 
   { 'Postman-Token': '452c9c1d-a70d-4a8b-9201-dc4328a875e7',
     'cache-control': 'no-cache',
     'Content-Type': 'application/x-www-form-urlencoded',
     'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' },
  formData: 
   { email: 'xyz@gmail.com',
     password: 'xxxxx',
     } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

请告诉我如何用react native(在axios中)编写它。 下面是我使用的代码。

 axios({
            method: 'POST',
            url: "http://www.myurl.com",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                 "content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
              },    
            data: { 
              ent_email: "xyz@gmail.com",
              ent_password: "xxx",

            }
          }).then(function (response) {
            console.log(response)

          }) .catch(function (error) {
              console.log("!!!!!!!!!!!!!ERROR!!!!!!!!!!!\n")
            console.log(error);
          });

当我打印response.data时,显示的错误是:

{
    "err": {
        "code": 10,
        "msg": "Invalid inputs"
    },
    "args": "[]"
}

3 个答案:

答案 0 :(得分:2)

您没有在formdata中发送数据。

您可以使用此

const data = new FormData();
data.append('ent_email', "xyz@gmail.com");
  data.append('ent_password', "xxx");
...
 axios({
            method: 'POST',
            url: "http://www.myurl.com",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                 "content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
              },    
            data: data
          }).then(function (response) {
            console.log(response)

          }) .catch(function (error) {
              console.log("!!!!!!!!!!!!!ERROR!!!!!!!!!!!\n")
            console.log(error);
          });

答案 1 :(得分:1)

如前所述,通过formData发送时,您需要使用POST。您不需要GET个请求。

我创建了一个简单的函数,供在React Native中使用axios时使用-它允许您指定请求类型并为params传递普通对象-如果您指定POST请求formData为您创建对象可以节省一些时间。

import axios from 'axios';

// Send a GET/POST request to the server and return the data (or true) upon completion
export async function asyncAjax( type, url, param_obj = {}, return_data = true )
{

    // Create an empty object to hold the request
    let res = {};
    const AXIOS_REQ_OBJ = axios.create( global.REQUEST_CONFIG );
    url = global.REQ_URL + url;

    // We need to use a try/catch as the request can throw
    try {
        switch( type )
        {
            case 'GET':
                // Create an empty array to hold each query string params
                let query_arr = [];

                // Loop through each of the parameters, concatenate them and add them to the query array
                Object.keys( param_obj ).forEach( key => {
                    query_arr.push( key + '=' + param_obj[ key ] );
                });

                // Make the GET request by building up the URL querystring (joining all of the params from the query_arr)
                res = await AXIOS_REQ_OBJ.get( url + '?' + query_arr.join('&'), {}, global.REQUEST_CONFIG );
                break;
            case 'POST':
                // Create a new form object for the request
                let form_data = new FormData();

                // Loop through each of the paramaters that have been provided and append them to the form object
                let has_data = false;
                Object.keys( param_obj ).forEach( key => {
                    has_data = true;
                    form_data.append( key, param_obj[ key ] );
                });

                // Make the POST request and set the response into variable
                res = has_data ? await AXIOS_REQ_OBJ.post( url, form_data, global.REQUEST_CONFIG ) : await AXIOS_REQ_OBJ.post( url, {}, global.REQUEST_CONFIG );
                break;
        }

        // If the calling function does not require the data, just return true as it has worked
        if( !return_data )
            return true;

        // Check that the response has data a valid JSON response
        let response_data = res.data;

        //  Return the data from the request back to the calling  function
        return await response_data;
    } catch( e ) {
        console.log( e );
    }
}

答案 2 :(得分:0)

    var bodyFormData = new FormData();            
    bodyFormData.append('email',this.state.email);
    bodyFormData.append('session_token',this.state.session_token);

    let response = await axios({
      method: 'post',
      url: 'http://yourapi.com',
      data: bodyFormData,
      config: { headers: {'Content-Type': 'multipart/form-data' }}
      })

上述解决方案对我有用。