【问题标题】:How to parse data from POST request如何从 POST 请求中解析数据
【发布时间】:2016-12-02 21:02:17
【问题描述】:

我有一个 getter 上下文:HTTP::Server::Context 和一个登录表单。
现在我想从 context.request.body 中解析数据以获取用户输入的用户名和密码。

响应的内容类型:application/x-www-form-urlencoded

【问题讨论】:

  • 请发布您到目前为止所尝试的内容。
  • 我使用 HTTP::Params 尝试解析 request.body 但结果为 nil。
  • 您没有告诉我们回复的内容类型,而是here you can see how to parse a JSON response
  • @mgarciaisaia 内容类型:application/x-www-form-urlencoded

标签: crystal-lang


【解决方案1】:

HTTP::Params.parse 就是你要找的东西:

# Based on the sample code in https://crystal-lang.org/ home
require "http/server"

server = HTTP::Server.new(8080) do |context|
  context.response.content_type = "text/plain"
  if body = context.request.body
    params = HTTP::Params.parse(body)
    context.response.print "Hello #{params["user"]? || "Anonymous"}!"
  else
    context.response.print "You didn't POST any data :("
  end
end

puts "Listening on http://127.0.0.1:8080"
server.listen

【讨论】:

  • 非常感谢。
  • 实际上我使用 crouter 进行路由,但我尝试使用 HTTP::Params 解析 request.body 并生成错误:没有重载匹配 'HTTP::Params.parse' 类型。但是我的错误是crouter已经有一个params变量,要获取body数据,只需像你一样使用params[“user”],不需要再次解析数据。
  • 是的 - 人们会期望解析这些选项是框架将为您做的事情之一。这是“动手”的方法——你的框架可能会调用这个函数。很高兴它有帮助,无论如何:)
  • 谢谢mgarciaisaia,祝你周末愉快:)
猜你喜欢
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多