Node.js中使用Axios如何实现URL动态传参完成手机号批量校验
实现方案
你可以通过遍历手机号数组动态生成请求参数,推荐直接使用axios内置的params配置项处理URL参数,不需要手动拼接字符串,避免编码错误。以下是两种常用的实现方式:
1. 并行请求(适合手机号数量少、接口无并发限制场景)
一次性发起所有校验请求,处理速度更快:
// 固定配置项 const BASE_URL = 'http://apilayer.net/api/validate' const ACCESS_KEY = '******' // 待校验手机号数组 const phoneList = ['14158586273', '13800138000', '13900139000'] // 批量生成请求实例 const requestList = phoneList.map(phone => { return axios.get(BASE_URL, { params: { access_key: ACCESS_KEY, number: phone, country_code: '', format: 1 } }) }) // 统一处理所有返回结果 Promise.all(requestList) .then(results => { results.forEach((res, index) => { console.log(`手机号${phoneList[index]}校验结果:`, res.data) }) }) .catch(err => { console.log('请求异常:', err) })
2. 串行请求(适合手机号数量多、需规避接口限流场景)
前一个请求完成后再发起下一个,单个请求报错不会中断整体任务:
const BASE_URL = 'http://apilayer.net/api/validate' const ACCESS_KEY = '******' const phoneList = ['14158586273', '13800138000', '13900139000'] async function batchValidate() { for (let phone of phoneList) { try { const res = await axios.get(BASE_URL, { params: { access_key: ACCESS_KEY, number: phone, country_code: '', format: 1 } }) console.log(`手机号${phone}校验结果:`, res.data) } catch (err) { console.log(`手机号${phone}校验失败:`, err) } } } batchValidate()
内容的提问来源于stack exchange,提问作者Predictev
相关产品推荐
相关产品推荐

