PHP can not get react Native fecth parameters Solution _php Instance

Source: Internet
Author: User

`

Without saying much, let's look at the sample directly



React Native uses afetchnetwork request, thePromiserecommended form for data processing.



The official Demo is as follows:


Fetch (' https://mywebsite.com/endpoint/', {method 
 : ' POST ',
 headers: {
 ' Accept ': ' Application/json ',
 ' content-type ': ' Application/json ',
 },
 body:JSON.stringify ({
 username: ' Yourvalue ', pass
 : ' Yourothervalue ',
 })
}. Then ((response) => Response.json ())
. Then ((res) => {
 Console.log (res);
})
. catch ((Error) => {
 Console.warn (error);
});


But actually in the development of the time, but found that PHP printed out$_POSTas an empty array.



This time I went to search for the next two solutions:



First, building form data


function toquerystring (obj) {return 
 obj? Object.keys (obj). sort (). map (function (key) {
  var val = obj[key];
  if (Array.isarray (val)) {return
   val.sort (). Map (function (val2) {return
    encodeURIComponent (key) + ' = ' + encodeURIComponent (VAL2);
   }). Join (' & ');
  }

  return encodeURIComponent (key) + ' = ' + encodeURIComponent (val);
 }). Join (' & '): ';
}

Fetch


But this does not work on its own machine.



Second, the service end solution



To get the contents of the body, you can write this in PHP:


$json = Json_decode (file_get_contents (' Php://input '), true);


This is the time to print out the data. Our problem, however, is that the service-side interfaces are all ready, and not only need to support the iOS side, but also the support of the Web and Android. This time to do compatible with our proposal is as follows:



1, wefetchset the set in the parameters of theheaderappfield, add theappname:ios-appname-1.8;



2. We set up a hook at the service end: Data processing before each request:


Gets the app for data set processing
  if (!function_exists (' apache_request_headers ')) {
   $appName = $_server[' app '];
  } else{
   $appName = apache_request_headers () [' app '];
  }

  To decode the RN fetch parameter
  if ($appName = = ' Your settings ') {
   $json = file_get_contents (' php://input ');
   $_post = Json_decode ($json, TRUE);
  }


This will not require big changes in the service side.



Simple encapsulation of the fetch



Since our front end was more with jquery, we did a simplefetchencapsulation:


var App = {

 config: {

  api: 'your host',
  // app version number
  version: 1.1,

  debug: 1,
 },

 serialize: function (obj) {
  var str = [];
  for (var p in obj)
   if (obj.hasOwnProperty (p)) {
    str.push (encodeURIComponent (p) + "=" + encodeURIComponent (obj [p]));
   }
  return str.join ("&");
 },

 // build random number
 random: function () {
  return ((new Date ()). getTime () + Math.floor (Math.random () * 9999));
 },



 // core ajax handler
 send (url, options) {
  var isLogin = this.isLogin ();
  var self = this;


  var defaultOptions = {
   method: 'GET',
   error: function () {
    options.success (('errcode': 501, 'errstr': 'System is busy, please try later');
   },
   headers: {
    'Authorization': 'your token',
    'Accept': 'application / json',
    'Content-Type': 'application / json',
    'App': 'your app name'
   },
   data: {
    // prevent ajax cache if not set
    '_regq': self.random ()
   },
   dataType: 'json',
   success: function (result) {}
  };

  var options = Object.assign ((}, defaultOptions, options);
  var httpMethod = options ['method']. toLocaleUpperCase ();
  var full_url = '';
  if (httpMethod === 'GET') {
   full_url = this.config.api + url + '?' + this.serialize (options.data);
  } else {
   // handle some to 'POST'
   full_url = this.config.api + url;
  }

  if (this.config.debug) {
   console.log ('HTTP has finished% c' + httpMethod + ':% chttp: //' + full_url, 'color: red;', 'color: blue;');
  }
  options.url = full_url;


  var cb = options.success;

  // build body data
  if (options ['method']! = 'GET') {
   options.body = JSON.stringify (options.data);
  }

  // todo support for https
  return fetch ('http: //' + options.url, options)
    .then ((response) => response.json ())
    .then ((res) => {
     self.config.debug && console.log (res);
     if (res.errcode == 101) {
      return self.doLogin ();
     }

     if (res.errcode! = 0) {

      self.handeErrcode (res);
     }
     return cb (res, res.errcode == 0);
    })
    .catch ((error) => {
     console.warn (error);
    });
 },


 handeErrcode: function (result) {
  //
  if (result.errcode == 123) {


   return false;
  }

  console.log (result);
  return this.sendMessage (result.errstr);
 },


 // prompt class

 sendMessage: function (msg, title) {
  if (! msg) {
   return false;
  }
  var title = title || 'Prompt';

  AlertIOS.alert (title, msg);
 }

};

module.exports = App; 


So developers can use this:


App.send (url,{ 
 success:function (res,issuccess) {
 }
})


Summarize



Okay, here PHP can not get react Native fecth parameters of the problem on the end of the basic solution, I hope this article for everyone's study and work to help, if there are questions or questions can be exchanged messages.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.