Ohos.permission.INTERNET permissions need to be configured. Locate the module.json5 file in the project directory entry\src\main and configure the network request permissions.
{ “module”: { “name”: “entry”, “type”: “entry”, “description”: “$string:module_desc”, “mainElement”: “EntryAbility”, “deviceTypes”: [ “phone” ], “requestPermissions”: [ { “name”: “ohos.permission.INTERNET” } ] } }
Simple to use
Import axios from ‘@ohos/axios’//Create instance of axios const instance = axios.create(“BaseURL:” http://xx.xx.xx.xx ,”//base path, depending on the characteristics of the APIs help document to determine the base path timeout: 5000,//request timeout headers:” Content-Type “:” Application/json “”)
The//response interceptor further processes the returned data through the response interceptor. Instance.interceptors.response.use response =>//only returns the result that the interface has data if 200 = response.status return response.data;//data returned by the interface return Promise.reject response;//indicates that the request has an error, and the request is sent to the catch for processing. Err => err.
/**
- Get Request
- @param params = Query Parameters
- @returns */ export function httpGet(url:string, params = {}) { return instance.get(url, { params }) }
/**
- Post Request
- @param data = Request Body Data
- @returns */ export function httpPost(url:string, data = {}) { return instance.post(url, { data }) }
Package and use of the axios module
Axios module package:
//AxiosHttp.ets
import axios, { AxiosInstance, AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse, InternalAxiosRequestConfig } from “@ohos/axios”; import { LogUtils } from ‘…/utils/LogUtils’;
/**
- Define Interface Response Wrap Class */export interface BaseResponse//wanAndroid-API Response Body errorCode: number errorMsg: string//Extended xxx-API Response Body
/**
- Interface implementation class wrapper. For example, other services can inherit the implementation xxxResponse */export interface ApiResponse<gt r=//wanAndroid-API response body data: T | again. Any;//expand xxx-API Response Body
/**
- After encapsulation, incoming blockers are not supported
- Need to define the interface inheritance AxiosRequestConfig type.
- This supports incoming blockers, but blocker options should be optional
- Options passed in by request instance later inherits custom type */of AxiosRequestConfig
This document is transferred from https://blog.csdn.net/2401_83947353/article/details/137568259,If there is any infringement,Please contact to delete。