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

React中使用Fetch发起GET请求时如何传递路径变量键值对?

How to Pass Key-Value Pairs in Path Variables with Fetch

Hey there! Let's get your Fetch request sorted out so you can pass those key-value pairs correctly. Based on typical Postman setups, I'll walk you through two common scenarios:

1. RESTful Path Parameters (Embedded in URL Path)

If your API expects key-value pairs directly in the URL path (like http://localhost:4000/restaurant/item/findAll/{category}/{status} where category and status are your variables), you can use JavaScript template literals to dynamically build the URL:

componentDidMount(){
  // Define your key-value pairs as variables
  const categoryId = 1;
  const itemStatus = "active";
  
  // Build the full URL by replacing placeholders with actual values
  const requestUrl = `http://localhost:4000/restaurant/item/findAll/${categoryId}/${itemStatus}`;
  
  fetch(requestUrl)
    .then(response => response.json())
    .then(data => { console.log(data) })
    .catch(error => console.error('Oops, something went wrong:', error));
}

This replaces the placeholder :1 in your original code with real, dynamic values that match your key-value pairs.

2. Query String Parameters (Key-Value Pairs After ?)

If your Postman setup uses the "Params" tab to add key-value pairs (which turn into a query string like ?id=1&type=main), you have two clean ways to handle this:

This built-in API automatically handles character encoding and formatting, so you don't have to worry about edge cases:

componentDidMount(){
  // Create a URLSearchParams object with your key-value pairs
  const searchParams = new URLSearchParams({
    id: 1,
    type: "main"
  });
  
  // Build the full URL by appending the query string
  const requestUrl = `http://localhost:4000/restaurant/item/findAll?${searchParams.toString()}`;
  
  fetch(requestUrl)
    .then(response => response.json())
    .then(data => { console.log(data) })
    .catch(error => console.error('Fetch error:', error));
}

Option B: Manually Build the Query String

If you prefer a more explicit approach, you can map over your object to create the query string:

componentDidMount(){
  const params = { id: 1, type: "main" };
  
  // Encode keys and values to avoid invalid URL characters
  const queryString = Object.keys(params)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&');
  
  const requestUrl = `http://localhost:4000/restaurant/item/findAll?${queryString}`;
  
  fetch(requestUrl)
    .then(response => response.json())
    .then(data => { console.log(data) })
    .catch(error => console.error('Fetch error:', error));
}

Just match the approach to how your API expects the key-value pairs (check your Postman request's final URL to confirm which format it uses!).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:42:36