首页 > 解决方案 > 在 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);

标签: node.jshttpflutterdart

解决方案


你必须自己做这项工作。

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

推荐阅读