如何解析POST请求中的数据

时间:2016-12-02 21:02:17

标签: crystal-lang

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

回复的内容类型:application / x-www-form-urlencoded

1 个答案:

答案 0 :(得分:4)

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