如何从API返回的redirect_uri URL中提取code参数?
问题原因及解决方案
你当前的问题出在直接将完整URL字符串传给URLSearchParams构造函数,它不会正确解析URL中的查询参数部分,而是把整个URL当作一组键值对处理,导致get('code')返回null。
正确的两种实现方式:
方式1:使用URL对象的searchParams属性(推荐)
通过URL对象解析完整URL,直接调用其内置的searchParams来获取参数,这是最可靠的方法:
.then((data) => { console.log(data); const redirect_uri = data.redirect_uri.toString(); const urlObj = new URL(redirect_uri); const code = urlObj.searchParams.get('code'); console.log(code); // 现在能正确获取到code值 })
方式2:手动提取查询字符串部分
先拆分URL,取出?后面的查询字符串,再传给URLSearchParams:
.then((data) => { console.log(data); const redirect_uri = data.redirect_uri.toString(); // 拆分URL,获取?后的查询字符串(兼容无?的情况) const queryString = redirect_uri.includes('?') ? redirect_uri.split('?')[1] : ''; const urlParams = new URLSearchParams(queryString); const code = urlParams.get('code'); console.log(code); })
为什么原代码无效?
当你执行new URLSearchParams(redirect_uri)时,构造函数会把完整URL"https://sitehere.sitehere.com?code=U78StlK6sN3hD9CO4ZogvpXvxezFSGU0"错误解析为一组键值对:
- 键:
https://sitehere.sitehere.com?code - 值:
U78StlK6sN3hD9CO4ZogvpXvxezFSGU0
所以调用get('code')时找不到对应的键,自然返回null。
内容的提问来源于stack exchange,提问作者David Verduzco
相关产品推荐
相关产品推荐

