react native axiosパッケージコンポーネント
一、最近react nativeのネットリクエストを研究して、それから自分で1つをカプセル化して練習します
1.axiosおよびquerystring依存の追加
yarn add axios && yarn add querystring
2.新規
1.axiosおよびquerystring依存の追加
yarn add axios && yarn add querystring
2.新規
src/common/httpBaseConfig.js
3. src/utils/http/index.js
import
axios
from
'axios';
import
qs
from
'querystring';
import
baseConfig
from
'../../common/httpBaseConfig.js';
axios.
defaults.
baseURL =
baseConfig.
baseUrl +
baseConfig.
prefix;
axios.
defaults.
timeout =
100000
// // axios
axios.
interceptors.
request.
use(
config
=> {
//
config.
headers[
'Authorization'] =
"12233334"
config.
headers[
'token'] =
"rreebjjj"
if(
config.
method ===
'get'){
config.
params = {
...
config.
data,
_t:
Date.
parse(
new
Date())/
1000
}
}
return
config
})
axios.
interceptors.
response.
use(
response
=> {
//
//console.log(response)
if(
response.
status ===
'200' ||
response.
status ===
200){
return
response.
data.
data ||
response.
data
}
else{
// 200
throw
Error(
response.
opt ||
' ')
}
})
// fetch , , axios, es7 。
export
default
class
http {
static
async
get(
url,
params) {
/**
* params{
* goods:id,
* name:string
* } ==> ?goods=id&name=string
*/
try {
let
query =
await
qs.
stringify(
params)
let
res =
null;
if (!
params) {
res =
await
axios.
get(
url)
}
else {
res =
await
axios.
get(
url +
'?' +
query)
}
return
res
}
catch (
error) {
return
error
}
}
static
async
post(
url,
params) {
try {
let
res =
await
axios.
post(
url,
params)
return
res
}
catch (
error) {
return
error
}
}
static
async
patch(
url,
params) {
try {
let
res =
await
axios.
patch(
url,
params)
return
res
}
catch (
error) {
return
error
}
}
static
async
put(
url,
params) {
try {
let
res =
await
axios.
put(
url,
params)
return
res
}
catch (
error) {
return
error
}
}
static
async
delete(
url,
params) {
/**
* params
*/
try {
let
res =
await
axios.
post(
url,
params)
return
res
}
catch (
error) {
return
error
}
}
}
4.