英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论