How to request localhost API from Android emulator?
Change the API endpoints in your Android code to http://10.0.2.2
How to GET json data?
- Define an API request function by fetch or axios
export const getMovies = () => {
const promise = new Promise((resolve, reject) => {
const success = (response) => {
resolve(response.json());
};
const fail = (error) => {
console.error(error);
reject(error);
};
fetch('https://facebook.github.io/react-native/movies.json')
.then(success)
.catch(fail);
});
return promise;
};
export const getMovies = () => {
const promise = new Promise((resolve, reject) => {
const success = (response) => {
resolve(response.json());
};
const fail = (error) => {
console.error(error);
reject(error);
};
axios.get('https://facebook.github.io/react-native/movies.json')
.then(success)
.catch(fail);
});
return promise;
};
- Call this function
useEffect(() => {
const getMoviesList = async () => {
try {
const response = await getMovies();
const movies = response.movies;
console.log('======', movies)
} catch(error) {
console.log('======', error)
}
};
getMoviesList();
}, []);
How to GET XML data?
Use react-native-xml2js to convert XML to JSON
function getMoviesFromApiAsync() {
const parseString = require('react-native-xml2js').parseString;
fetch('link')
.then(response => response.text())
.then((response) => {
parseString(response, function (err, result) {
return result;
}).catch((err) => {
console.log('fetch', err)
})
}
How to POST form data?
Fetch
export const login = async (username, password) => {
const formData = new URLSearchParams();
formData.append('username', b64EncodeUnicode(username));
formData.append('password', b64EncodeUnicode(password));
formData.append('token', API_TOKEN);
const url = API_BASE_URL + API_LOGIN;
try {
const response = await fetch(url, {
method: 'POST',
body: formData.toString(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
});
...
} catch (error) {
console.log(error);
}
};
export const b64EncodeUnicode = (str) => {
return btoa(
encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
return String.fromCharCode('0x' + p1);
}),
);
};
Axios
const url = API_BASE_URL + API_LOGIN_AND_GET_CARD;
const formData = new URLSearchParams();
formData.append('username', b64EncodeUnicode(username));
formData.append('password', b64EncodeUnicode(password));
formData.append('token', API_TOKEN);
const headers = {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
};
axios.post(url, formData, headers)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
How to POST with “raw json” payload – Auth key is as “Bearer”?
export const authRequestWithJson = (endpoint, body, token) => {
const url = endpoint.toLowerCase()
fetch(url,
{
method: 'POST',
body: JSON.stringify({ name: 'json format'}), // Need to convert JSON to string!!
headers: {
'Content-Type': 'application/json', // Need to set THIS!!
'Authorization': `Bearer ${token}`
}
})
.then(response => {
if (response.status >= 400 && response.status < 600) {
throw new Error(`Failed ${url}, got status ${response.status}`)
}
const contentType = response.headers.get('content-type')
if (!contentType || contentType === 'text/plain') {
return response
}
try {
return response.json()
} catch (e) {
return response
}
})
.catch(error => {
return Promise.reject(error)
})
}
const body = `{
"id": 1,
"name": "${(username)}"
}`
authRequestWithJson('https://xxxx.xx/api/savesomething', body, bearerToken)
How to fix CORS issue?
How to create Axios instance?
// Declare
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
// Use
instance.get(apiUri, {
timeout: 5000,
})
.then(success)
.catch(fail);
How to intercept failed request and retry it?
Use axios-retry
What do you need to retry a request?
- Retry delay
- Retry number
- Retry condition (when should it do a retry)
- Timeout between retries
- A callback to notify when a retry is about to occur
Leave a Reply