在javascript中获取api中的url查询字符串

时间:2016-01-09 10:52:35

标签: javascript google-chrome fetch-api

如何使用fetch api javascript(https://github.com/github/fetch)传递查询字符串?

var url = "http://www.abcd.com";
var query = {
    a: "test",
    b: 2
};

当我将一些参数传递给http://www.abcd.com?a=test&b=2

时,上面应该转换为fetch

1 个答案:

答案 0 :(得分:6)

var params = Object.keys(query)
                   .map((key) => encodeURIComponent(key) + "=" + encodeURIComponent(query[key]))
                   .join("&")
                   .replace(/%20/g, "+");

fetch(url + "?" + params);

或使用options对象 - but this will NOT work with GET and HEAD method

fetch(url, {
    method: "POST",
    body: convertObjectToFormData(query)
}).then(...);

function convertObjectToFormData(obj) {
    var formData = new FormData();
    for (var key in obj) {
        formData.append(key, obj[key]);
    }
    return formData;
}