JavaScript将object对象拼接成URL问号后面的字符串

需求:

假设有个一变量

params = {
	a: 1
	b: '',
	c: '铁公鸡'
}

想拼接在已知url='http://localhost:8080/api/get/'后面,变成
http://localhost:8080/api/get/?a=1&b=&c=xxx

方案一:采用axios

import axios from 'axios'
let url='http://localhost:8080/api/get/'
const params = {
	a: 1,
	b: '',
	c: '铁公鸡'
}
url = axios.getUri({ url, params })
console.log(url)

方案二:自己手动拼接

let url='http://localhost:8080/api/get/'
const params = {
	a: 1,
	b: '',
	c: '铁公鸡'
}
url = url + '?' + Object.keys(params).map(i => `${i}=${encodeURIComponent(params[i]||'')}`).join('&')
console.log(url)
// http://localhost:8080/api/get/?a=1&b=&c=%E9%93%81%E5%85%AC%E9%B8%A1

明明这么简单的功能,为什么搜索到的解决方案,大部分是很多行代码的呢,奇怪。

附:对于axios方案,如果变量名不是url和params,则需这样调用:

const path = 'https://api.com/path'
const query = {'a': null, 'b': undefined, 'c': false, 'd': '中文', 'e': '', 'f': 0}
const fullUrl = axios.getUri({ url: path, params: query })
console.log(fullUrl)
// https://api.com/path?c=false&d=%E4%B8%AD%E6%96%87&e=&f=0
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值