PHP獲取不了React Native Fecth參數(shù)的解決辦法
話不多說,我們直接來看示例
React Native 使用 fetch 進(jìn)行網(wǎng)絡(luò)請求,推薦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('&') : '';
}
// fetch
body: 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、我們在fetch參數(shù)中設(shè)置了 header 設(shè)置 app 字段,加入app名稱:ios-appname-1.8;
2、我們在服務(wù)端設(shè)置了一個(gè)鉤子:在每次請求之前進(jìn)行數(shù)據(jù)處理:
// 獲取 app 進(jìn)行數(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ù)端就無需做大的改動(dòng)了。
對 Fetch的簡單封裝
由于我們的前端之前用 jquery較多,我們做了一個(gè)簡單的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)繁忙,請稍候嘗試'});
},
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é)束了,希望本文對大家的學(xué)習(xí)與工作能有所幫助,如果有疑問或者問題可以留言進(jìn)行交流。
相關(guān)文章
PHP魔術(shù)方法以及關(guān)于獨(dú)立實(shí)例與相連實(shí)例的全面講解
下面小編就為大家?guī)硪黄狿HP魔術(shù)方法以及關(guān)于獨(dú)立實(shí)例與相連實(shí)例的全面講解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-10-10
php實(shí)現(xiàn)支付寶當(dāng)面付(掃碼支付)功能
這篇文章主要為大家詳細(xì)介紹了php實(shí)現(xiàn)支付寶當(dāng)面付,掃碼支付功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05
在IIS7.0下面配置PHP 5.3.2運(yùn)行環(huán)境的方法
最近心血來潮,想學(xué)習(xí)一下php,既然想學(xué)習(xí)了就得需要搭環(huán)境。在網(wǎng)上找來找去都是說IIS5.0或者6.0的配置。真是看得云里霧里的,這樣直接影響了我的判斷力?,F(xiàn)特意寫下來在IIS7.0下面如何進(jìn)行配置PHP。2010-04-04
PHP in_array()函數(shù)基本語法及嚴(yán)格比較使用實(shí)例
PHP是一種常用的服務(wù)器端腳本語言,提供了豐富的內(nèi)置函數(shù)來簡化開發(fā)過程,其中,in_array()函數(shù)是一種非常有用的函數(shù),用于判斷數(shù)組中是否存在指定的值,本文將詳細(xì)介紹in_array()函數(shù)的用法,并提供具體的代碼示例2024-01-01
thinkPHP3.x常量整理(預(yù)定義常量/路徑常量/系統(tǒng)常量)
這篇文章主要介紹了thinkPHP3.x常量,整理總結(jié)了thinkPHP3.x常用的各類常量,包括預(yù)定義常量、路徑常量及系統(tǒng)常量,需要的朋友可以參考下2016-05-05

