- axios 是一个基于promise的网络请求库
- 安装 三方工具 axios
ohpm install @ohos/axios
import axios, { AxiosResponse, FormData } from '@ohos/axios'
const TAG = "huxiubo"
@Entry
@Component
struct Index {
@State user:gData = null
@State pData: pData = null;
// get 请求
getUserinfo() {
console.info(TAG, `getUerinfo`);
axios.get("http://192.168.0.113:8080/userinfo")
.then((res: AxiosResponse<gData>) => {
console.info(TAG, `Successed ${JSON.stringify(res.data)}`);
this.user = res.data
})
.catch((err: Error) => {
console.error(TAG, `error: ${JSON.stringify(err)}`)
})
}
// post请求
postData() {
let form = new FormData()
form.append('firstName', 'hu')
form.append('lastName', 'xiubo')
console.info(TAG, `${JSON.stringify(form)}`);
axios.post("http://192.168.0.113:8080/addName", form)
.then((res: AxiosResponse) => {
console.info(TAG, `Successed ${JSON.stringify(res.data)}`);
this.pData = res.data
console.info(TAG, `Successed ${this.pData.fName}`);
})
.catch((err: Error) => {
console.error(TAG, `error: ${JSON.stringify(err)}`)
})
}
build() {
Column({space:15}) {
Text(`get请求结果: ${this.user ? this.user.name :""}`)
Text(`post请求结果 ${this.pData ? this.pData.fName: ""}`)
Button("get")
.onClick(()=> {
this.getUserinfo()
})
Button("post")
.onClick(()=> {
this.postData()
})
}
.width('100%')
.height('100%')
}
}
interface user {
firstName:string,
lastName: string
}
class gData {
name: string;
data: string;
}
class pData {
fName: string;
lName: string;
}
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
server := gin.Default()
//get 请求
server.GET("/userinfo", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"name": "hongmeng",
"data": "2023-10-11",
})
})
// post
server.POST("/addName", func(ctx *gin.Context) {
firstName := ctx.PostForm("firstName")
lastName := ctx.PostForm("lastName")
ctx.JSON(200, gin.H{
"fName": firstName + " server",
"lName": lastName + " server",
})
fmt.Printf(" %s ", firstName)
})
server.Run()
}