You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在URL中传递数组?附前端API查询调用代码示例

Hey there! Let's work through how to properly pass an array in your URL to the API for filtering. Your current code uses JSON.stringify for the search parameter, but we can refine this to be more robust and aligned with common API practices.

Option 1: Use repeated query parameters (most API-friendly)

This is the standard approach most backend frameworks expect for array parameters. We'll use URLSearchParams to safely build the query string, which handles encoding automatically:

handleFilter = (search, page = 1) => {
  const params = new URLSearchParams();
  
  // Add each array item as a separate `search` parameter
  if (Array.isArray(search)) {
    search.forEach(item => params.append('search', item));
  } else {
    // Fallback for non-array search values (like a single string)
    params.append('search', search);
  }
  
  params.append('page', page);

  const requestOption = { method: "GET" };
  fetch(`http://127.0.0.1:8000/api/home?${params}`, requestOption)
    .then(res => {
      // Add a check for successful responses
      if (!res.ok) throw new Error(`HTTP error! Status: ${res.status}`);
      return res.json();
    })
    .then(data => this.setState({ data }))
    .catch(err => console.error('Failed to fetch filtered data:', err));
};

This will generate a URL like http://127.0.0.1:8000/api/home?search=value1&search=value2&page=1, which frameworks like Express, Django, or Rails can directly parse into an array for the search parameter.

Option 2: Keep using JSON string (if your backend requires it)

If your API is specifically built to accept a JSON string for the search parameter, we can still clean up the code with URLSearchParams to avoid manual string concatenation and encoding issues:

handleFilter = (search, page = 1) => {
  const params = new URLSearchParams({
    search: JSON.stringify(search),
    page: page
  });

  const requestOption = { method: "GET" };
  fetch(`http://127.0.0.1:8000/api/home?${params}`, requestOption)
    .then(res => {
      if (!res.ok) throw new Error(`HTTP error! Status: ${res.status}`);
      return res.json();
    })
    .then(data => this.setState({ data }))
    .catch(err => console.error('Failed to fetch filtered data:', err));
};

This ensures the JSON string is properly URL-encoded, so your backend can safely decode it and parse the array.

Key Notes:

  • Check your backend's expected format: Confirm whether your API expects repeated parameters or a JSON string for array inputs. The first option is more widely supported.
  • Add error handling: I added checks for HTTP errors and a catch block to handle network issues—this prevents silent failures in your app.
  • Type safety: The array check ensures you don't run into issues if search is ever a non-array value.

内容的提问来源于stack exchange,提问作者josh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:54:18