解決PHP獲取不了 React Native Fecth參數的問題

React Native 使用 fetch 進行網絡請求,推薦Promise的形式進行數據處理。官方的 Demo 以下:javascript

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打印出 $_POST爲空數組。這個時候本身去搜索了下,提出了兩種解決方案: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)

參考這裏前端

可是這個在本身的機器上並不生效。java

服務端解決方案

獲取body裏面的內容,在php中能夠這樣寫:react

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

這個時候就能夠打印出數據了。然而,咱們的問題是 服務端的接口已經所有弄好了,並且不單單須要支持ios端,還須要web和Android的支持。這個時候要作兼容咱們的方案大體以下:jquery

  1. 咱們在fetch參數中設置了 header 設置 app 字段,加入app名稱:ios-appname-1.8;ios

  2. 咱們在服務端設置了一個鉤子:在每次請求以前進行數據處理:git

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

這樣服務端就無需作大的改動了。github

對 Fetch的簡單封裝

因爲咱們的前端以前用 jquery較多,咱們作了一個簡單的fetch封裝:web

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':'系統繁忙,請稍候嘗試'});
            },
            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;

這樣開發者能夠這樣使用:

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

更多內容詳見: https://github.com/JackPu/react-native-core-lib

相關文章
相關標籤/搜索