首页 > 解决方案 > 在 get 方法中发送带有参数的对象

问题描述

我有这个接收这个过滤器参数的get方法,它是一个带有from的对象,我想将它们作为url中的参数传递

export async function queryEventTimelineFilteredAPI(filter) {
  
  console.log('componentManager', filter)

  
  const response = await fetch('/api/v1/data/queryEventTimeline', {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' }
  })
  return await response.json();
}

标签: javascriptnode.jsexpress

解决方案


用于JSON.stringify()将其转换为 JSON,encodeURIComponent()添加%特殊字符的正确编码,然后将其连接到 URL。

不需要Content-type标头,因为 GET 请求没有内容。

export async function queryEventTimelineFilteredAPI(filter) {
  
  console.log('componentManager', filter)

  const response = await fetch('/api/v1/data/queryEventTimeline?filter=' +  encodeURIComponent(JSON.stringify(filter)), {
    method: 'GET',
  })
  return await response.json();
}

请注意,URL 长度通常非常有限,因此 JSON 过滤器不应很大。最好将其作为 POST 数据发送。


推荐阅读