使用反应原生的fetch polyfill将数据作为键值对发送

jis*_*isu 1 http react-native fetch-api

以下代码是使用fetch polyfill发出HTTP POST请求:

fetch(url, {
  method: 'post',
  body: JSON.stringify({
    'token': this.state.token
  })
})
  .then((response) => response.json())
  .then((responseData) => {
    console.log(responseData)
  })
  .done();
Run Code Online (Sandbox Code Playgroud)

此请求将数据作为字符串化的json obj发送.有没有办法将数据作为键值对发送,类似于python中的requests.post(url,data = payload).

Col*_*say 8

听起来你想要一个与查询字符串相同的格式,所以导入/需要像https://www.npmjs.com/package/query-string这样的包,它似乎不依赖于任何浏览器功能,并且有一个stringify方法:

queryString.stringify({
    foo: 'bar',
    nested: JSON.stringify({
        unicorn: 'cake'
    })
});

//=> foo=bar&nested=%7B%22unicorn%22%3A%22cake%22%7D 
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用其源代码的相关部分,但这仍然需要获得许可:

function toQueryString(obj) {
    return obj ? Object.keys(obj).sort().map(function (key) {
        var val = obj[key];

        if (Array.isArray(val)) {
            return val.sort().map(function (val2) {
                return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
            }).join('&');
        }

        return encodeURIComponent(key) + '=' + encodeURIComponent(val);
    }).join('&') : '';
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在body参数中使用返回值fetch:

fetch(url, {
  method: 'post',
  body: toQueryString({ 'token': this.state.token })
})
Run Code Online (Sandbox Code Playgroud)