【问题标题】:Vapor: sending post requestsVapor:发送 post 请求
【发布时间】:2022-01-06 23:29:19
【问题描述】:

我正在尝试使用 Vapor 发送 HTTP 请求,以验证 recaptcha

Google's Captcha api定义如下:

网址:https://www.google.com/recaptcha/api/siteverify 方法:发布

POST Parameter Description
secret Required. The shared key between your site and reCAPTCHA.
response  Required. The user response token provided by the reCAPTCHA client-side integration on your site. 
remoteip Optional. The user's IP address. 

所以我需要使用 2 个参数(秘密和响应)发出 POST 请求。

在 Swift 中我有:

func routes(_ app: Application throws {
    app.on(.POST, "website_form") { req -> EventLoopFuture<View> in
        var form: FromRequest = /*initial values*/
        /*decode form data*/
        
        do {
            req.client.post("https://www.google.com/recaptcha/api/siteverify") { auth_req in
                try auth_req.content.encode(CaptchaRequestBody(secret: "6Lfoo98dAAAAALRlUoTH9LhZukUHRPzO__2L0k3y", response: form.recaptcha_response), as: .formData)
                auth_req.headers = ["Content-Type": "application/x-www-form-urlencoded"]
            }.whenSuccess { resp_val in
                print("Response: \(resp_val)")
            }
        }
    } 
    /* More code */
}

struct CaptchaRequestBody: Content {
    let secret: String
    let response: String
}

运行 post 请求后,我收到以下错误代码:

{
  "success": false,
  "error-codes": [
    "missing-input-secret"
  ]
}

我找不到任何有效的解决方案,即使官方的 Vapor 文档也没有用,有人可以帮帮我吗?

【问题讨论】:

  • 如果将编码类型更改为 .urlEncodedForm 而不是 .formData 会发生什么?
  • 您可能需要发送/接收原始数据(八位字节流)。 Vapor 通常只允许你发送接收 JSON 数据(字符串)。可以发送接收原始数据,但不是那么简单
  • @Nick 解决了这个问题!我在两者之间感到困惑。谢谢。

标签: swift server recaptcha vapor


【解决方案1】:

Google API 要求请求是 URL 编码的表单。通过使用 .formData 设置,您正在强制执行 MultiPart。

将设置更改为.urlEncodedForm,以确保请求符合 Google API 要求。

【讨论】:

    【解决方案2】:

    正如尼克所说:问题是我需要使用.urlEncodedForm,而不是.formData

    【讨论】:

    • @Nick 感谢您的提示!
    猜你喜欢
    • 2018-11-02
    • 1970-01-01
    • 2016-01-25
    • 2017-07-13
    • 2010-10-12
    • 2016-03-24
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多