| 版權聲明:本文爲博主原創文章,未經博主允許不得轉載。
一、簡介
幾乎所有的應用都需要和服務器端進行交互,以此從服務器端獲取各種數據。RN中網絡請求簡單明瞭並且支持多種請求方式。下面讓我們一起看看官方標準的網絡請求方法(fetch)如何使用。
二、基礎知識
- fetch方法支持GET和POST請求方式
- 第一個參數輸入URL,第二個參數用來自定義HTTP請求,添加自定義的請求頭或者POST請求傳遞的參數
三、應用
- 請求方式
// GET請求
fetch(url, { method: 'GET' })
// POST請求 formData爲表單格式傳遞的參數
fetch(url, {
method: 'POST',
body: formData
})
- 結果處理
// 發送請求!
function getMoviesFromApiAsync() {
let url = 'https://facebook.github.io/react-native/movies.json';
//傳遞參數使用FormData對象
let formData = new FormData();
formData.append("username", 'admin');
loginForm.append("password", '123456');
return fetch(url, {
method: 'POST',
headers: {},
body: formData
})
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
// 調用發送請求並處理服務器返回數據的方式
getMoviesFromApiAsync()
.then((responseJson) => {
// TODO handle data
})
.catch((error) => {
// TODO handle error
});
- GET請求處理方式同上,只需將method屬性改成GET並去掉參數即可