【问题标题】:Force query parameter format in url在 url 中强制查询参数格式
【发布时间】:2020-10-15 16:02:42
【问题描述】:

我的颤振应用程序中有一个方法可以通过将参数传递到 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);

【问题讨论】:

    标签: node.js http flutter dart


    【解决方案1】:

    您必须自己完成这项工作。

    URI 查询参数放在 URI 的 query 部分。

    Uri 类不知道您的服务也在 URI 的非查询部分接受其参数。如果你想让某些东西成为 URI 的 path 的一部分,你必须把它放在那里。

    所以,类似:

      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);
      }
    

    【讨论】:

    • 谢谢...我不认为我能做到这一点,所以我创建了新方法getById 但我宁愿问以防万一这可能以某种方式.. 谢谢为了保证
    猜你喜欢
    • 2018-10-14
    • 2015-08-17
    • 2010-10-31
    • 2020-01-16
    • 1970-01-01
    • 2017-06-20
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多