我在处理多个参数时遇到了麻烦。通过一个我很好,但我不确定传递多个。我在网页上有这个JS代码:
$.getJSON('api/vendor/countryVendors/'+country+'&'+resourceType, function(result){}
以下在我的Vapor控制器中:
func getcountryVendors(_ req: Request) throws -> Future<[Vendor]> {
let countryString = try req.parameters.next(String.self)
let resourceTypeString = try req.parameters.next(String.self)
不确定我创建的URL是错误的还是我的Swift代码或两者兼而有之
看起来你正试图传递query-string parameters,这与route path parameters不同。在这种情况下,两个片段都是错误的。
查询字符串参数是附加到URL末尾的键/值对,如下所示:
/my/url/path?key=value&key1=value1
因此,您的JS代码中的URL应如下所示:
'api/vendor/countryVendors?country='+country+'&resourceType='+resourceType
要从传递给路由处理程序的URL获取查询字符串参数,请使用request.query
属性和.get(_:at:)
方法:
func getcountryVendors(_ req: Request) throws -> Future<[Vendor]> {
let countryString = try req.query.get(String.self, at: "country")
let resourceTypeString = try req.query.get(String.self, at: "resourceType")
// Other code...
}