最近在學習react-native,遇到調用后端接口的問題.看了看官方文檔,推薦使用es6的fetch來與后端進行交互,在網上找了一些資料.在這里整理,方便以后查詢.
1.RN官方文檔中,可使用XMLHttpRequest
var request = new XMLHttpRequest(); request.onreadystatechange = (e) => { if (request.readyState !== 4) { return; } if (request.status === 200) { console.log('success', request.responseText); } else { console.warn('error'); } }; request.open('GET', 'https://mywebsite.com/endpoint.php'); request.send();
這是http的原生方法,這里不做多的介紹.
2.RN官方文檔中,推薦使用fetch
fetch('https://mywebsite.com/endpoint/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ firstParam: 'yourValue', secondParam: 'yourOtherValue', }) }).then(function(res){
body中的數據就是我們需要向服務器提交的數據,比如用戶名,密碼等;如果上述body中的數據提交失敗,那么你可能需要把數據轉換成如下的表單提交的格式:
console.log(res)
})
fetch('https://mywebsite.com/endpoint/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: 'key1=value1&key2=value2' })
.then(function(res){
console.log(res)
})
這樣可以獲取純文本的返回數據.
如果你需要返回json格式的數據:fetch(
'
https://mywebsite.com/endpoint/
'
).then(
function
(res) {
if
(res.ok) {
res.json().then(
function
(obj) {
// 這樣數據就轉換成json格式的了
})
}
},
function
(ex) {
console.log(ex)
})
fetch模擬表單提交:
fetch(
'doAct.action'
, {
method:
'post'
,
headers: {
"Content-type"
:
"application/x-www-form-urlencoded; charset=UTF-8"
},
body:
'foo=bar&lorem=ipsum'
})
.then(json)
.then(
function
(data) {
console.log(
'Request succeeded with JSON response'
, data);
})
.
catch
(
function
(error) {
console.log(
'Request failed'
, error);
});