我的flutter应用程序中有一个方法,用于通过将参数传递到url来查询get请求
Future<Map<String, dynamic>> getData(
{String path, String token, Map<String, String> params}) async {
try {
Uri uri = Uri.parse(path);
Uri newUri = uri.replace(queryParameters: params); // http://some/path/?param=1...
final http.Response response =
await http.get(newUri, headers: APIHeader.authorization(token));
final jsonResponse = json.decode(response.body);
if (response.statusCode != 200) {
throw ServerException(jsonResponse["error"]);
}
return jsonResponse['result'];
} catch (error) {
throw error;
}
}
Uri
方法生成的网址是http://some/path/?param=1...
它工作正常,但是如果我只想使用它通过id查询,则查询参数格式仅是idhttp://some/path/1
如果我使用上述方法并以{'id':'1'}
格式发送参数,那么我会得到urlhttp://some/path/?id=1
有没有办法在我的后端强制将参数设置为../?id=1
格式,或者有什么办法使Uri
方法识别这些差异?我的ID的后端路由器是
router.get('/some/path/:id', controller.get);
最佳答案
您必须自己进行这项工作。
URI查询参数放入URI的查询部分。Uri
类并不了解您的服务还在URI的非查询部分中接受其参数。如果要使某些内容成为URI路径的一部分,则必须将其放在其中。
因此,类似:
Uri addParameters(Uri baseUri, Map<String, String> params) {
if (query.length == 1 && params.containsKey("id")) {
// ID only. Assume baseUri ends in `/`.
return baseUri.resolve(params["id"]);
}
return baseUri.replace(queryParameters: params);
}
关于node.js - 强制使用网址中的查询参数格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62571246/