gin 框架 post 方法 获取请求参数为空

770 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第7天,点击查看活动详情

今天在写接口的时间发现了一个有意思的 事情,在vue 中用axios 发送的 post请求,打到 接口上时候,用context.PostForm("key") 取值时候,竟然取不到值。至于原因是什么,我们来一步一步排查。

如果你也遇到了这个问题,可以直接关注下 在请求时候 post 中 data 的数据类型。 直接滑倒文档底部,可以看到解决方法,用的是qs库 ,格式化了data的数据格式。

go server:


r.POST("/login", func(context *gin.Context) {
   username := context.PostForm("username")
   password := context.PostForm("password")
   fmt.Printf("username :%s \t password : %s \n",username,password)
   context.JSON(http.StatusOK,gin.H{
      "username":username,
      "password":password,
   })
})

原来的请求

sentpost() {
      this.axios
        .post("http://127.0.0.1:8000/login", {
          username: "xiaoming",
          password: "123456",
        })
        .then((response) => {
          console.log(response.data);
        })
        .catch(function (error) {
          console.log(error);
        });
},

image.png

image.png

what happend ?

数据去哪里了?

再去用curl 试一下

image.png

这大概率不是gin的解析的问题,因为经过搜索🔍,发现这个问题根本找不到答案。那应该大概率是发送的请求的问题,那咱们就用接口工具🧰,来测试一下。

image.png

image.png 什么情况有数据了?

这时候 我关注到了,post 发送数据时候的数据格式问题。

image.png

post data 数据格式

multipart/form-data

image.png

application/w-www-form-urlencoded

image.png

application/json

image.png

application/xml

image.png

application/javascript

image.png

text/plain

image.png

text/html

image.png

**我们发现部分 格式的data 数据才能的到正确的返回。**然后我就开始怀疑data 数据格式的问题了。

最终决绝方法

image.png

使用了qs 库 给data 数据格式化一下发送就可以解析了。