Why are null and undefined variables removed from params
Problem
https://github.com/axios/axios/blob/638804aa2c16e1dfaa5e96e68368c0981048c4c4/lib/helpers/buildURL.js#L38 I would expect [code block] To construct `?a=&b=`
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Modify Axios URL Builder to Include Null and Undefined Params
The current implementation of the Axios URL builder removes parameters that are null or undefined when constructing the query string. This behavior is due to the use of the `filter` method, which excludes any entries that are falsy, including null and undefined values. As a result, parameters that are explicitly set to null or undefined do not appear in the final URL, leading to unexpected query strings.
Awaiting Verification
Be the first to verify this fix
- 1
Update buildURL Function
Modify the buildURL function to include parameters that are explicitly set to null or undefined. Instead of filtering out falsy values, check for the existence of the parameter key and include it in the query string if it exists.
javascriptfunction buildURL(url, params) { const parts = []; for (const key in params) { const value = params[key]; if (value !== undefined) { parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); } else { parts.push(encodeURIComponent(key) + '='); // Include null/undefined as empty string } } return url + '?' + parts.join('&'); } - 2
Test the Updated Function
Create unit tests to ensure that the modified buildURL function correctly includes parameters set to null or undefined in the query string. This will help verify that the fix works as intended.
javascripttest('buildURL includes null and undefined params', () => { const result = buildURL('http://example.com', { a: null, b: undefined }); expect(result).toBe('http://example.com?a=&b='); }); - 3
Review and Merge Changes
Once the tests pass, review the changes for any potential side effects and merge them into the main branch. Ensure that the documentation is updated to reflect the new behavior of the buildURL function.
Validation
Run the unit tests created in step 2 to confirm that the buildURL function now includes parameters that are null or undefined in the constructed URL. Additionally, manually test the function with various combinations of parameters to ensure expected behavior.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep