无法读取参数

huangapple go评论81阅读模式
英文:

unable to read params

问题

我通过axios发送了一个POST请求,因为我需要发送body和params。然而,当请求到达后端时,params参数不见了!

async getAll(page: number, pageSize: number, filter: IFilter): Promise<Course[]> {
    const res = await request.post<{ data: Course[]; metadata: 'none' }>("/v1/courses", {
        params: {
            page: page,
            pageSize: pageSize,
        },
        data: filter,
    });

    return res.data.data;
}

浏览器控制台的网络选项卡显示如下:

{params: {page: 1, pageSize: 6},}
data: 
{all: true, beginner: false, intermediate: false, advanced: false, amqp: false, databases: false,}
params: 
{page: 1, pageSize: 6}

代码片段:

func (app *Courses) CoursesAllHandler(w http.ResponseWriter, r *http.Request) {
    ctx := context.Background()

    clog := log.GetLoggerFromContext(ctx)

    p := r.URL.Query().Get("page")
    ps := r.URL.Query().Get("pageSize")

    var filter Filter
    err := json.NewDecoder(r.Body).Decode(&filter)
    if err != nil {
        http.Error(w, "Failed to parse request body", http.StatusBadRequest)
        return
    }
}

对我来说,axios的调用看起来是正确的,后端获取参数的方法也是正确的。然而,当我查看网络选项卡并看到dataparams时,我想知道是否需要更深入地查看。所以我尝试了以下代码:

p := r.URL.Query().Get("data") // 空值

Filter结构体定义如下:

type Filter struct {
    All          bool `json:"all"`
    Beginner     bool `json:"beginner"`
    Advanced     bool `json:"advanced"`
    Intermediate bool `json:"intermediate"`
    Go           bool `json:"go"`
}

如果有任何建议,我将不胜感激。

---- 更新 ----

请求转储:

request, err := httputil.DumpRequest(r, true)
if err != nil {
    return
}

clog.Info(string(request))

输出结果如下:

(KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36\r\n\r\n{"params":{"page":1,"pageSize":6},"data":{"all":true,"beginner":false,"intermediate":false,"advanced":false,"amqp":false,"databases":false,"docker":false,"gcp":false,"go":false,"grpc":false,"java":false,"mux":false,"serverless":false,"vue":false,"spring":false}}
英文:

I send a request via axios as a post because I need to send a body and params. However when it reaches my backend the params are not there!

async getAll(page: number, pageSize: number, filter: IFilter): Promise&lt;Course[]&gt; {
    const res = await request.post&lt;{ data: Course[]; metadata: &#39;none&#39; }&gt;(&quot;/v1/courses&quot;, {
        params: {
            page: page,
            pageSize: pageSize,
        },
        data: filter,
    });

    return res.data.data;
}

Network tab in the browser console

{params: {page: 1, pageSize: 6},…}
data: 
{all: true, beginner: false, intermediate: false, advanced: false, amqp: false, databases: false,…}
params: 
{page: 1, pageSize: 6}

snippet

func (app *Courses) CoursesAllHandler(w http.ResponseWriter, r *http.Request) {
    ctx := context.Background()

    clog := log.GetLoggerFromContext(ctx)

    p := r.URL.Query().Get(&quot;page&quot;)
    ps := r.URL.Query().Get(&quot;pageSize&quot;)

    var filter Filter
    err := json.NewDecoder(r.Body).Decode(&amp;filter)
    if err != nil {
        http.Error(w, &quot;Failed to parse request body&quot;, http.StatusBadRequest)
        return
    }

To me the axios call looks correct and the params method to get them in the backend as well. However when I look at the Network tab and see data: and params I wounder if I need to go deeper. So I tried:

p := r.URL.Query().Get(&quot;data&quot;) &lt;--- empty


type Filter struct {
	All          bool `json:&quot;all&quot;`
	Beginner     bool `json:&quot;beginner&quot;`
	Advanced     bool `json:&quot;advanced&quot;`
	Intermediate bool `json:&quot;intermediate&quot;`
	Go           bool `json:&quot;go&quot;`
}

Any advice would be appreciated.

---- update ---

request dump

request, err := httputil.DumpRequest(r, true)
if err != nil {
	return
}

clog.Info(string(request))

(KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36\r\n\r\n{\&quot;params\&quot;:{\&quot;page\&quot;:1,\&quot;pageSize\&quot;:6},\&quot;data\&quot;:{\&quot;all\&quot;:true,\&quot;beginner\&quot;:false,\&quot;intermediate\&quot;:false,\&quot;advanced\&quot;:false,\&quot;amqp\&quot;:false,\&quot;databases\&quot;:false,\&quot;docker\&quot;:false,\&quot;gcp\&quot;:false,\&quot;go\&quot;:false,\&quot;grpc\&quot;:false,\&quot;java\&quot;:false,\&quot;mux\&quot;:false,\&quot;serverless\&quot;:false,\&quot;vue\&quot;:false,\&quot;spring\&quot;:false}}&quot;}

答案1

得分: 1

你为什么要查看 r.URL.Query() 来获取 POST 参数?你需要做类似这样的操作:

type Request struct {
    Params struct {
        Page     int `json:"page"`
        PageSize int `json:"pageSize"`
    } `json:"params"`
    Data Filter `json:"data"`
}

var req Request

err := json.NewDecoder(r.Body).Decode(&req)

这段代码定义了一个名为 Request 的结构体,其中包含了 ParamsData 两个字段。Params 字段是一个嵌套结构体,包含了 PagePageSize 两个整型字段,它们分别对应 JSON 中的 "page""pageSize" 键。Data 字段则是一个名为 Filter 的类型。

接下来,通过 json.NewDecoder(r.Body).Decode(&req) 将请求体中的 JSON 数据解码到 req 变量中。这样你就可以方便地访问 POST 参数了。

英文:

Why are you looking at r.URL.Query() to get POST params? You need to do something like:

type Request struct {
    Params struct {
        Page int `json:&quot;page&quot;`
        PageSize int `json:&quot;pageSize&quot;`
    } `json:&quot;params&quot;`
    Data Filter `json:&quot;data&quot;`
}

var req Request

err := json.NewDecoder(r.Body).Decode(&amp;req)

huangapple
  • 本文由 发表于 2023年7月19日 00:00:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76714645.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定