PHP获取不了React Native Fecth参数的解决办法

2025-05-29 0 71

话不多说,我们直接来看示例

React Native 使用 fetch 进行网络请求,推荐Promise的形式进行数据处理。

官方的 Demo 如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
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为空数组。

这个时候自己去搜索了下,提出了两种解决方案:

一、构建表单数据

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
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)

但是这个在自己的机器上并不生效。

二、服务端解决方案

获取body里面的内容,在php中可以这样写:

?

1

2
$json = json_decode(file_get_contents('php://input'), true);

var_dump($json['username']);

这个时候就可以打印出数据了。然而,我们的问题是 服务端的接口已经全部弄好了,而且不仅仅需要支持ios端,还需要web和Android的支持。这个时候要做兼容我们的方案大致如下:

1、我们在fetch参数中设置了 header 设置 app 字段,加入app名称:ios-appname-1.8;

2、我们在服务端设置了一个钩子:在每次请求之前进行数据处理:

?

1

2

3

4

5

6

7

8

9

10

11

12
// 获取 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 );

}

这样服务端就无需做大的改动了。

对 Fetch的简单封装

由于我们的前端之前用 jquery较多,我们做了一个简单的fetch封装:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123
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;

这样开发者可以这样使用:

?

1

2

3

4
App.send(url,{

success: function(res,isSuccess) {

}

})

总结

好了,到这里PHP获取不了React Native Fecth参数的问题就基本解决结束了,希望本文对大家的学习与工作能有所帮助,如果有疑问或者问题可以留言进行交流。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 PHP获取不了React Native Fecth参数的解决办法 https://www.kuaiidc.com/96873.html

相关文章

发表评论
暂无评论