如何解析POST请求中的数据

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

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

回答(1)

2 years ago

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