Swift服务端框架Vapor实现GET请求
2018-04-18 本文已影响74人
狂奔的胖蜗牛
前提条件:请参考我的文章再次使用Swift服务端框架Vapor3
什么是GET请求
- GET请求是HTTP协议中的一个方法。
- GET从服务器上获取数据,也就是所谓的查,仅仅是获取,并不会修改数据。
- GET交互方式是幂等的,即多次对同一个URL的请求,返回的数据是相同的。
- GET请求的参数会附加在URL之后,以?分割URL和传输数据,多个参数用&连接。
- GET请求URL编码格式采用的是ASCII编码,而不是Unicode,所有非ASCII字符都要编码之后再传输。
- GET请求传输数据大小不能超过2KB。
- GET请求安全性低,因为是明文传输。
创建项目
#1.打开终端
#2.创建项目
vapor new HelloVapor --branch=beta
这个过程会花费十来分钟的样子。最终成功后结果如图:

#3.进入项目
cd HelloVapor
#4.构建项目,这一步也会花费比较久时间,建议使用VPN。
vapor build
#5.运行项目
vapor run
运行完毕后,如图所示:

此时,我们打开浏览器,浏览:
http://localhost:8080/hello
点击后如图所示:

#6.关闭vapor的运行,使用组合键:Control+C即可
#7.创建出xcode能运行的项目
vapor xcode -y
运行完毕后,Xcode会自动打开项目。
实现GET请求
进入项目中,Sources/App/Routes目录中,找到Routes.swift文件。删除掉setupRoutes()方法中的内容,添加代码,最终Routes.swift内容如下:
import Vapor
extension Droplet {
func setupRoutes() throws {
/*
路由关闭的情况:
1.响应了请求
2.抛出异常
*/
//最基本的GET请求
get("welcom") { request in
return "Hello"
}
//URL中包含了/
get("foo", "bar", "baz") { request in
return "You request /foo/bar/baz"
}
//动态路由到某个HTTP方法
add(.get, "hh") { request in
return "Dynamically router"
}
//重新定向
get("baidu") { request in
return Response(redirect: "http://www.baidu.com")
}
//返回json数据
get("json") { request in
var json = JSON()
try json.set("number", 123)
try json.set("text", "unicorns")
try json.set("bool", false)
return json
}
//模糊匹配路径
get("anything", "*") { request in
return "Matches anything anything/anything route"
}
//404错误
get("404") { request in
throw Abort(.notFound)
}
//错误的请求
get("error") { request in
throw Abort(.badRequest)
}
}
}
我们依次在浏览器中输入如下链接可以看到结果:
http://localhost:8080/welcom
http://localhost:8080/foo/bar/baz
http://localhost:8080/hh
http://localhost:8080/baidu
http://localhost:8080/json
http://localhost:8080/anything/a/b/c/d
http://localhost:8080/404
http://localhost:8080/error
结果依次如下所示:






错误:

