国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 語(yǔ)言 > PHP > 正文

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

2024-05-04 23:49:24
字體:
供稿:網(wǎng)友

話不多說,我們直接來看示例

React Native 使用 fetch 進(jìn)行網(wǎng)絡(luò)請(qǐng)求,推薦Promise的形式進(jìn)行數(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);});

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

這個(gè)時(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('&') : '';}// fetchbody: toQueryString(obj) 

但是這個(gè)在自己的機(jī)器上并不生效。

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

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

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

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

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

    2、我們?cè)诜?wù)端設(shè)置了一個(gè)鉤子:在每次請(qǐng)求之前進(jìn)行數(shù)據(jù)處理:

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

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

對(duì) Fetch的簡(jiǎn)單封裝

由于我們的前端之前用 jquery較多,我們做了一個(gè)簡(jiǎn)單的fetch封裝:

var App = { config: {  api: 'your host',  // app 版本號(hào)  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)繁忙,請(qǐ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  AlertIOS.alert(title,msg); }};module.exports = App;

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

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

總結(jié)

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


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到PHP教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 玉环县| 皋兰县| 平利县| 扎鲁特旗| 图片| 新巴尔虎左旗| 玛多县| 巧家县| 都江堰市| 黑龙江省| 长寿区| 漯河市| 大荔县| 乌拉特中旗| 冷水江市| 城口县| 来宾市| 宜春市| 樟树市| 平利县| 克什克腾旗| 鄂尔多斯市| 宝鸡市| 漳浦县| 河北省| 天津市| 天门市| 永新县| 镇原县| 扎赉特旗| 林甸县| 鲁山县| 恩施市| 平湖市| 永嘉县| 庄河市| 县级市| 郧西县| 石柱| 莆田市| 桃园县|