接收客户端数据 封面
Vapor 大型教程

接收客户端数据

接口不只是返回数据,还要能收数据。本文用 Vapor 的 Content 协议从 POST 请求中解码 JSON,拿到客户端传来的字段。

Content 协议:从请求中提取数据

Content 协议是 Vapor 对 Codable 协议的封装,用来从请求中提取数据。添加遵守 Content 协议的结构体 InfoData,它只有一个 name 字符串成员,Content 协议支持请求数据向结构体对象的解码转换。在 routes 文件中添加下面代码,编译运行。

POST 请求

import Vapor

func routes(_ app: Application) throws {
    app.get { req in
        return "It works!"
    }

    app.get("hello") { req -> String in
        return "Hello, world!"
    }

    // Add Routes
    app.get("hello", ":name") { req -> String in
        guard let name = req.parameters.get("name", as: String.self) else {
            return "\(HTTPStatus.notFound)"
        }
        return "Hello, \(name)"
    }
    // ---
    app.post("info") { req -> String in
        let info = try req.content.decode(InfoData.self)
        return "Hello, \(info.name)"
    }
}
struct InfoData: Content {
    let name: String
}

用 curl 测试路由

我们使用 curl 这个工具来测试我们的路由是否正常工作,这个工具是类 Linux 系统都自带的命令行工具,不存在收费问题,可以免费使用,而且学习后端是必须掌握这个命令行工具的使用方法的。

  • -X 表示请求类型:GET / POST / PUT / DELETE,默认为 GET
  • -H 请求发起时的 Headers 设置。
  • -d 请求发起时所携带的数据。

curl 测试命令:

curl http://localhost:8080/info \
-X POST \
-H "content-type:application/json" \
-d '{"name":"joker"}' 

输出:

Hello, joker

Rested(已弃用)

之前使用一个 Mac 上名叫 rested 的应用,模拟 POST 请求(现在这个 App 开始收费,不能免费使用了,并且在中国区无法下载)。

本系列其他文章