React中使用Fetch发起GET请求时如何传递路径变量键值对?
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:
Option A: Use URLSearchParams (Recommended)
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

