PHP cannot obtain the React Native Fecth parameter.

Source: Internet
Author: User

PHP cannot obtain the React Native Fecth parameter.

Let's look at the example.

Use React Nativefetch For network requests and recommendationsPromise.

The official Demo is as follows:

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

However, during actual development, I found that php prints $_POSTEmpty array.

At this time, I searched and proposed two solutions:

1. Construct form data

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) 

But this does not take effect on your own machine.

Ii. Server Solution

Obtain the content in the body, which can be written in php as follows:

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

At this time, you can print the data. However, our problem is that all the interfaces on the server have been completed, and not only support ios, but also support web and Android. At this time, we need to make the solutions compatible with Alibaba Cloud as follows:

1. We arefetchTheheader Setapp Field, addappName:ios-appname-1.8;

2. We set a hook on the server to process data before each request:

// Obtain the app for centralized data processing if (! Function_exists ('apache _ request_headers') {$ appName = $ _ SERVER ['app'];} else {$ appName = apache_request_headers () ['app'];} // decode the RN fetch parameter if ($ appName = 'your settings') {$ json = file_get_contents ('php: // input '); $ _ POST = json_decode ($ json, TRUE );}

In this way, the server does not need to be changed significantly.

Simple encapsulation of Fetch

Because our front-end has a lot of jquery before, we have made a simplefetchEncapsulation:

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 s End (url, options) {var isLogin = this. isLogin (); var self = this; var defaultOptions = {method: 'get', error: function () {options. success ({'errcode': 501, 'errstr': 'System busy. Please try later '}) ;}, 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) ;}, // The prompt class sendMessage: function (msg, title) {if (! Msg) {return false;} var title = title | 'hup'; AlertIOS. alert (title, msg) ;}}; module. exports = App;

In this way, developers can use:

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

Summary

Now, PHP cannot solve the problem of getting the React Native Fecth parameter. I hope this article will be helpful for your study and work, if you have any questions, leave a message.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.