Vapor:发送 post 个请求

Vapor: sending post requests

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

Google's Captcha api定义如下:

URL:https://www.google.com/recaptcha/api/siteverify 方法:POST

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 文档也没有用,有人可以帮助我吗?

正如 Nick 所说:问题是我需要使用 .urlEncodedForm.

而不是 .formData

Google API 要求请求为 URL 编码形式。通过使用 .formData 设置,您将强制执行 MultiPart。

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