国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

PHP獲取不了React Native Fecth參數(shù)的解決辦法

Original 2016-12-29 13:32:10 298
abstract:這篇文章的主要內(nèi)容是解決PHP獲取不了React Native Fecth參數(shù)的問題,本文通過示例詳細解釋如何解決這個問題,相信對大家的理解更有幫助,如果有這個問題的可以參考下本文,下面跟著小編一起來看看。React Native 使用 fetch 進行網(wǎng)絡(luò)請求,推薦Promise的形式進行數(shù)據(jù)處理。官方的 Demo 如下:fetch('https://mywebsit

這篇文章的主要內(nèi)容是解決PHP獲取不了React Native Fecth參數(shù)的問題,本文通過示例詳細解釋如何解決這個問題,相信對大家的理解更有幫助,如果有這個問題的可以參考下本文,下面跟著小編一起來看看。

React Native 使用 fetch 進行網(wǎng)絡(luò)請求,推薦Promise的形式進行數(shù)據(jù)處理。

官方的 Demo 如下:

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);
});

但是實際在進行開發(fā)的時候,卻發(fā)現(xiàn)了php打印出 $_POST為空數(shù)組。

這個時候自己去搜索了下,提出了兩種解決方案:

一、構(gòu)建表單數(shù)據(jù)

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
body: toQueryString(obj)

但是這個在自己的機器上并不生效。

二、服務(wù)端解決方案

獲取body里面的內(nèi)容,在php中可以這樣寫:

$json = json_decode(file_get_contents('php://input'), true);
var_dump($json['username']);

這個時候就可以打印出數(shù)據(jù)了。然而,我們的問題是 服務(wù)端的接口已經(jīng)全部弄好了,而且不僅僅需要支持ios端,還需要web和Android的支持。這個時候要做兼容我們的方案大致如下:

    1、我們在fetch參數(shù)中設(shè)置了 header 設(shè)置 app 字段,加入app名稱:ios-appname-1.8;

    2、我們在服務(wù)端設(shè)置了一個鉤子:在每次請求之前進行數(shù)據(jù)處理:

// 獲取 app 進行數(shù)據(jù)集中處理
  if(!function_exists('apache_request_headers') ){
   $appName = $_SERVER['app'];
  }else{
   $appName = apache_request_headers()['app'];
  }
 
  // 對 RN fetch 參數(shù)解碼
  if($appName == 'your settings') {
   $json = file_get_contents('php://input');
   $_POST = json_decode($json, TRUE );
  }

這樣服務(wù)端就無需做大的改動了。

對 Fetch的簡單封裝

由于我們的前端之前用 jquery較多,我們做了一個簡單的fetch封裝:

var App = { 
 config: { 
  api: 'your host',
  // app 版本號
  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':'系統(tǒng)繁忙,請稍候嘗試'});
   },
   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);
 },
 
 
 // 提示類
 
 sendMessage: function(msg,title) {
  if(!msg) {
   return false;
  }
  var title = title || '提示';
 
  AlertIOS.alert(title,msg);
 } 
}; 
module.exports = App;

這樣開發(fā)者可以這樣使用:

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

總結(jié)

好了,到這里PHP獲取不了React Native Fecth參數(shù)的問題就基本解決結(jié)束了,希望本文對大家的學習與工作能有所幫助,如果有疑問或者問題可以留言進行交流。

更多關(guān)于PHP獲取不了React Native Fecth參數(shù)的解決辦法請關(guān)注PHP中文網(wǎng)(www.miracleart.cn)其它文章!

Release Notes

Popular Entries