api.xxxxx.xx/problems/se…
場景:在請求的 API 中附帶參數,以?、&鏈接
推薦使用社區 npm 包: qs 或 query-string 實現該功能npm
const parseParams = (uri, params) => {
const paramsArray = []
Object.keys(params).forEach(key => params[key] && paramsArray.push(`${key}=${params[key]}`))
if (uri.search(/\?/) === -1) {
uri += `?${paramsArray.join('&')}`
} else {
uri += `&${paramsArray.join('&')}`
}
return uri
}
複製代碼
let params = {
keyword: 't',
page: 1,
size: 2
}
let uri = 'http://api.xxxxx.xx/problems/search'
parseParams(uri, params)
//http://api.xxxxx.xx/problems/search?keyword=t&page=1&size=2
複製代碼
urlEncode (params) {
let paramsArray = []
Object.keys(params).forEach(key => params[key] && paramsArray.push(`${key}=${params[key]}`))
return paramsArray.join('&')
}
複製代碼
let params = {
name: 'cs1'
email: 'cs1@cs1.com'
mobile: '1xxxxxxxxxx'
password: '123456'
password_confirmation: '123456'
captcha: 'xxhej'
}
parseParams(params)
//name=cs1&email=cs1@cs1.com&mobile=15603315002&password=123456&school=neuq&password_confirmation=123456&captcha=xxhej
複製代碼
const paramsArray = []
複製代碼
Object.keys(params).forEach(key => params[key] && paramsArray.push(`${key}=${params[key]}`))
複製代碼
if (uri.search(/\?/) === -1) {
uri += `?${paramsArray.join('&')}`
} else {
uri += `&${paramsArray.join('&')}`
}
return uri
複製代碼