《PHP編程:PHP獲取不了React Native Fecth參數(shù)的解決辦法》要點:
本文介紹了PHP編程:PHP獲取不了React Native Fecth參數(shù)的解決辦法,希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP編程話不多說,我們直接來看示例
PHP編程React Native 使用 fetch
進行網(wǎng)絡(luò)請求,推薦Promise
的形式進行數(shù)據(jù)處理.
PHP編程官方的 Demo 如下:
PHP編程
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);
});
PHP編程但是實際在進行開發(fā)的時候,卻發(fā)現(xiàn)了php打印出 $_POST
為空數(shù)組.
PHP編程這個時候自己去搜索了下,提出了兩種解決方案:
PHP編程一、構(gòu)建表單數(shù)據(jù)
PHP編程
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)
PHP編程但是這個在自己的機器上并不生效.
PHP編程二、服務(wù)端解決方案
PHP編程獲取body里面的內(nèi)容,在php中可以這樣寫:
PHP編程
$json = json_decode(file_get_contents('php://input'), true);
var_dump($json['username']);
PHP編程這個時候就可以打印出數(shù)據(jù)了.然而,我們的問題是 服務(wù)端的接口已經(jīng)全部弄好了,而且不僅僅需要支持ios端,還需要web和Android的支持.這個時候要做兼容我們的方案大致如下:
PHP編程??? 1、我們在fetch
參數(shù)中設(shè)置了 header
設(shè)置 app
字段,加入app
名稱:ios-appname-1.8
;
PHP編程????2、我們在服務(wù)端設(shè)置了一個鉤子:在每次請求之前進行數(shù)據(jù)處理:
PHP編程
// 獲取 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 );
}
PHP編程這樣服務(wù)端就無需做大的改動了.
PHP編程對 Fetch的簡單封裝
PHP編程由于我們的前端之前用 jquery較多,我們做了一個簡單的fetch
封裝:
PHP編程
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;
PHP編程這樣開發(fā)者可以這樣使用:
PHP編程
App.send(url,{
success: function(res,isSuccess) {
}
})
PHP編程總結(jié)
PHP編程好了,到這里PHP獲取不了React Native Fecth參數(shù)的問題就基本解決結(jié)束了,希望本文對大家的學(xué)習(xí)與工作能有所幫助,如果有疑問或者問題可以留言進行交流.
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/3977.html