我在一个项目中使用 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'
最佳答案
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'
如果要将查询字符串添加到获取请求中:
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)
这将产生一个请求:
关于javascript - 使用 fetch 发送带有数据对象的 get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39245994/