嘿伙计们我正在尝试从远程服务器获取数据并使用react-native
返回alertbox这是我提取的代码
_onPressButtonPOST: function(){
fetch("http://www.example.com/endpoint", {
method: "POST",
body: JSON.stringify({
key: "value",
})
})
.then((response) => response.json())
.then((responseData) => {
Alert.alert(
"POST Response",
"Response Body -> " + JSON.stringify(responseData.body)
)
})
.done();
},
这是我想从我的端点获取的内容。
{
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "service",
"_type": "service",
"_id": "ac8c5edd-1aad-406f-b476-012c6e940c1a",
"_score": 1,
"_source": {
"service_owner_id": "2",
"service_name": "miamia",
"service_email": "mk@gmail.com",
"service_contact_name": "mukesh",
"service_landline_number": "12345",
"service_mobile_number": "1234567890",
"service_address": "vdvml",
"service_listingType": 1,
"service_avg_rating": 3.5,
"sarvice_ratingcount": 10,
"service_serviceType": 1,
"service_working_hour": [
""
],
"service_subcat_ids": "2,3",
"service_description": "hi I am mukesh kumar ",
"service_id": "ac8c5edd-1aad-406f-b476-012c6e940c1a",
"service_logo_url": "",
"service_gallery_url": "",
"service_location": {
"lat": 19.34,
"lon": 72.845
},
"service_subcategory": "CAT GER ",
"service_review": []
}
}
]
},
"took": 2,
"timed_out": false
}
但是在alertbox中它显示未定义可能是什么问题?任何人都可以帮忙吗? 提前谢谢。
答案 0 :(得分:0)
嘿,伙计们,我发现了这个错误并成功使用了API,感谢https://www.thepolyglotdeveloper.com/2015/09/make-http-requests-in-ios-with-react-native/ 我刚刚用responseData替换了responseData.body,因为我的服务器端代码中没有包含任何主体,所以它返回undefined
这是我的示例代码
.then((response) => response.json())
.then((responseData) => {
Alert.alert(
"POST Response",
"Response Body -> " + JSON.stringify(responseData)
)
})
.done();
欢迎任何疑问和疑问。
答案 1 :(得分:0)
通常另一个原因是,在PHP端点代码中,他们尝试使用$ _POST,$ _GET或$ _REQUEST来获取发送的参数。
在这种情况下,代替Json,在获取操作中使用FormData作为正文值。
一个例子
var FormDataToPost = new FormData();
FormDataToPost.append('userId', 12);
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: FormDataToPost
})
.then((response) => response.json())
.then((responseData) => { do something })
.catch((error) => {
alert(error);
})
.done();