如何在 cordovaHTTP 插件请求中设置 Content-Type header

How to set Content-Type header in cordovaHTTP plugin requests

我正在尝试使用 cordovaHTTP 插件和 POST api 调用,尽管我已将 Content-Type header 设置为 application/json 但我可以看到内容以 application/x-www-form-urlencoded 格式发送,并且在 header 的请求中不存在 Content-Type header。

使用示例:

cordovaHTTP.post("url/to/method",
 {
   "email": "ali@aliha.me"
 },
 {
   "Content-Type": "application/json"
 },
 function (result) {
   alert('success');
 },
 function (error) {
   alert('error');
 });

在服务器中api我看到:

RAW BODY
email=ali%40aliha.me

如何设置Content-Typeheader?

注意: 这种设置 headers 的方法适用于其他 headers,例如 Authorization header.

插件中没有提到它会根据集合 "Content-Type" 自动对请求正文进行编码。你需要自己做。

此外,似乎没有直接的方法可以在不指定 key.value 对的情况下在请求正文中发送数据。

来自插件文档

/**
   * Write the values in the map as form data to the request body
   * <p>
   * The pairs specified will be URL-encoded in UTF-8 and sent with the
   * 'application/x-www-form-urlencoded' content-type
   *
   * @param values
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest form(final Map<?, ?> values) throws HttpRequestException {
    return form(values, CHARSET_UTF8);
  }

你可以用这种方式编码你的 json 字符串,但你必须想办法在请求正文中发送它

var jsonData = JSON.stringify({"email": "ali@aliha.me"});

此插件在其 post 方法中尚不支持 Content-Type header。
我使用了 forked repository from dear brendonparker 而不是 postJson 发送 post 请求的方法 content-type of application/json.