使用fetch向数据对象发送get请求

时间:2016-08-31 09:38:56

标签: javascript ajax fetch-api

我在项目中使用Fetch(Fetch API),为了保持一致,我想创建一个接收所有参数(如方法,url和数据)的函数,并创建正确的请求,具体取决于如果是GET或POST请求。

是否有可能使用Fetch发送一个数据对象,该数据对象用于GET请求,将数据转换为参数字符串并且如果它是POST请求,它只是在正文中发送数据对象?

看起来像这样:

fetch ('/test', {
        method: 'GET',
        data: {
           test: 'test'
        }
});

这个疑问的灵感来自于这个jQuery ajax行为:

$.ajax({
   url: '/test',
   method: 'GET',
   data: {
      test: 'test'
   }
});

这会产生这个请求:

'/test/?test=test'

2 个答案:

答案 0 :(得分:6)

If I pass the data object as normal in the fetch constructor for a GET request, would it send the request like the example I gave '/test/?test=test'

If you want to add query string to a fetch request :

From the SPEC

var url = new URL("https://a.com/method"),
params = {a:1, b:2}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url)

this will produce a request :

enter image description here

答案 1 :(得分:1)

you could either use the Url class:

var url = new URL("/test/")
Object.keys({test: 'test', a: 1}).forEach(key => url.searchParams.append(key, params[key]))
fetch(url);

or parse the string yourself, if you want wider browser support:

var params = {test: 'test', a: 1},
    qs = Object.keys(params).reduce(function(_qs, k, i){ return _qs + '&' + k + '=' + params[k]; }, '').substring(1);

console.log(qs)