1. 前端 vue 代码

    axios
        //.post("http://localhost:8888/ping", {
        .get("http://localhost:8888/ping", {
          params: {
            name: this.input_name,
            sex: this.input_sex
          }
        })
        .then(res => {
          console.log(res);
        })
        .catch(error => {
          console.log("网络请求错误", error);
        });
    }

2. 服务端 get 请求代码

  r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		name := c.Query("name")
		sex := c.Query("sex")
		fmt.Printf("name: %s; sex: %s", name, sex)
	})
  r.Run(":8888")

3. 服务端 post 请求代码

post请求需要考虑跨域问题

func main() {
	r := gin.Default()
	r.Use(Cors())
	r.POST("/ping", func(c *gin.Context) {
		buf := make([]byte, 1024)
		n, _ := c.Request.Body.Read(buf)
		c.Request.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
		j := buf[0:n]
		fmt.Println("body:", string(j)) //获取到post传递过来的数据

		var message Message
		err := json.Unmarshal(j, &message)
		if err != nil {
			fmt.Println("====>", err)
			return
		}
		fmt.Println("====>" + message.Name)

	})
	r.Run(":8888")
}

//Cors 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method

		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		c.Next()
	}
}