node.js - 在 url 中强制查询参数格式
问题描述
我的颤振应用程序中有一个方法可以通过将参数传递到 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
方法生成的url在哪里http://some/path/?param=1...
它工作正常但是如果我只想用它来查询 id 那么查询参数格式只是 id
http://some/path/1
如果我使用上面的方法并以格式发送参数,{'id':'1'}
那么我会得到 url
http://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);
}
推荐阅读
- html - 我的 Bootstrap 数据切换实现有什么问题?
- google-maps - 创建多维度交互图的工具推荐
- python - 优化 OpenCV 蒙版边缘
- json - Angular 6 错误处理 - HttpErrorResponse 具有未定义的状态
- symfony - 无法在 Symfony 中向模型添加字段,bin/console 崩溃
- semaphore - signal() 和 wait() 在信号量算法中做吗?
- python - python + google sheet == gspread,但遗憾的是AttributeError:类型对象'ServiceAccountCredentials'没有属性'from_json_keyfile'
- r - 在 Shinyapps 上运行应用程序的问题(传单地图贴错标签)
- swift - UIButton 调整大小以适应 UIImage
- python - 如何解码 LTTextLine.get_text() 的输出?