package main
import "github.com/kataras/iris/v12"
func main(){
app := iris.New()
//Get请求
app.Get("/",func(ctx iris.Context){
ctx.Text("你好,这是首页")
})
//Post请求
app.Post("/postTest",func(ctx iris.Context){
name := ctx.PostValue("name") //通过PostValue(requestName)这个api进行获取
ctx.Text(name)//用文本响应
})
//监听端口
app.Listen(":8088")
}
因为iris中我们没有做跨域处理所以我们在
vite.config.ts(vite.config.js)
中做处理
import { defineConfig } from 'vite'
import path from "path"
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server:{
proxy: {
'/my-api-go':{
target: "http://localhost:8088/",
changeOrigin:true,
rewrite: path => path.replace(/^\/my-api-go/,'')
}
}
}
})
<script setup lang="ts">
import {ref,reactive,Ref} from "vue"
import axios from "axios"
import qs from 'qs'
const username:Ref<string> = ref('')
const pwd: Ref<string> = ref('')
const value:Ref<string> = ref('')
const testBtn01 = () => {
axios.get('/my-api-test01/test01').then(async (res:any)=>{
console.log(res.data)
}).catch((err:any)=>{
console.log(err)
})
}
const postBtn01 = () => {
// 将参数转换成功 formdata 接收格式
function stringify (data:any) {
const formData = new FormData()
for (const key in data) {
// eslint-disable-next-line no-prototype-builtins
if (data.hasOwnProperty(key)) {
if (data[key]) {
if (data[key].constructor === Array) {
if (data[key][0]) {
if (data[key][0].constructor === Object) {
formData.append(key, JSON.stringify(data[key]))
} else {
data[key].forEach((item, index) => {
formData.append(key + `[${index}]`, item)
})
}
} else {
formData.append(key + '[]', '')
}
} else if (data[key].constructor === Object) {
formData.append(key, JSON.stringify(data[key]))
} else {
formData.append(key, data[key])
}
} else {
if (data[key] === 0) {
formData.append(key, 0)
} else {
formData.append(key, '')
}
}
}
}
return formData
}
axios({
method: 'post',
url: '/my-api-go/postTest',
data:{
name: username.value
},
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest:{
function(data:any){
return stringify(data)
}
},
transformResponse:{
async function(data:any){ //async await:异步阻塞
value.value = await data
return data
}
}
})
}
}
script>
<template>
<div>
<div>
<input type="text" placeholder="用户名" v-model="username"/><br />
<button @click="postBtn01()">提交button>
<p>{{value}}p>
div>
div>
template>
<style scoped>
style>
注意点
stringify函数
:不需要注意, 复制粘贴即可axios({})
method
:请求方式,可以是get
,post
,put
,options
url
:请求api的路径data
:传输的参数与go中的获取参数名称(PostValue中的name和data中的name:''
)要一致否则后端还是获取不到transformRequest
:发送请求时处理transformResponse
:接收响应时处理