当请求来自go的NewRequestWithContext时,在Rails中的post参数为空。

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

Empty post params in rails when the request came from go NewRequestWithContext

问题

我正在使用Rails 5从Go脚本获取一个POST请求,我有一个路由将POST请求发送到我的函数。

在Go脚本中,我使用以下代码进行POST请求并发送数据:

request, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(data))
resp, err := client.Do(request)

在Rails中,我使用以下代码获取POST请求的参数:

params = params.permit!.except(:controller, :action).to_h

问题是当我从Go发送请求时,params是空的{}

但是我可以通过在Rails中执行以下操作来查看请求的原始主体数据:

puts request.raw_post

在Rails中:

request.headers["Content-Type"]:
"text/plain; charset=utf-8"

在Go中的数据:

data, err := json.Marshal(jsonData)

以上是要翻译的内容。

英文:

I am using rails 5 to get a post request from go script, i have a route with post to my function.

In go script, i am using this code to do post request and send the data:

request, err := http.NewRequestWithContext(ctx, post, url, bytes.NewBuffer(data))
resp, err := client.Do(request)

In rails, I using this code to get the parameters of the post request

params = params.permit!.except(:controller, :action).to_h

The pb is that params are empty {} when i do the request from go.

But i can see the data in request raw body by doing in rails:

puts request.raw_post

In rail:

  request.headers["Content-Type"]: 
  "text/plain; charset=utf-8" 

Data in go :

data, err := json.Marshal(jsonData)

答案1

得分: 1

我必须在Go中的请求中提供正确的ContentType头部。代码如下:

request.Header.Set("Content-Type", "application/json")

由于我发送的是JSON数据,所以ContentType是"application/json"。如果不设置正确的ContentType,Rails将无法理解请求体,并且无法使用params参数。

英文:

I must provide the correct ContentType header with the request in go by do

request.Header.Set("Content-Type", "application/json")

It is json as i am sending json. If not the case, rails will not understand the request body and will not be able to use params.

huangapple
  • 本文由 发表于 2021年8月5日 23:33:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/68669522.html
匿名

发表评论

匿名网友

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

确定