我在对象中收集了一些数据,并且该数据动态更新。关键是我已经根据这些数据动态调整了网址。
var cookie = context.Request.Cookies.Get(".AspNetCore.Bearer");
var ticket = cookie.Value;
ticket = ticket.Replace('-', '+').Replace('_', '/');
var padding = 3 - ((ticket.Length + 3) % 4);
if (padding != 0)
{ ticket = ticket + new string('=', padding); }
var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
var decoded = secureDataFormat.Unprotect(ticket);
当对象获得新值时,我需要动态发送新请求
答案 0 :(得分:2)
所有答案(目前有4个)说明了使用注入的参数来塑造URL字符串的各种方法。
它们都是合法的方法,但是我认为从阅读您的问题开始,除了重塑字符串之外,您还需要侦听包含参数的实际对象的更改。
我认为解决此问题的最佳方法是侦听来自将启动运行功能的服务器的答复:
const setUrl(res){
myObj.val1 = res.val1;
myObj.val2 = res.val2;
myObj.val3 = res.val3;
url = // Whatever method you want to use to set the url.
}
但是,由于您没有在代码中说过要这样做,所以我还要补充一点,您还可以“监听”对象本身的更改,并在更改时触发不同的setUrl()
函数发生。
为此:
// Make an Object:
const obj = {};
// Make a url variable:
let url = '';
// Make a function to set url:
const setUrl = ()=>{
url = `http://www.example.com?val1=${obj.val1}&val2=${obj.val2}`; // Or whatever method you prefer to build the string.
}
// Make an Object Proxy and inject it with the setUrl() method:
const objProx = new Proxy(obj, {
set(obj, prop, newVal) {
// Here you inject some action to take place whenever the set method is invoked on the obj via the proxy.
setUrl();
return obj[prop] = newVal;
},
});
// Now all that is left to do is make sure that you set the properties of obj via the objProxy:
objProxy.val1 = "parameter1";
objProxy.val2 = "parameter2";
答案 1 :(得分:1)
您可以使用reduce将对象转换为url字符串,如下所示:
let myObj = {
val1: 'someVal1',
val2: 'someVal2',
val3: [10, 39],
val4: 'test&test'
};
const myUrl = Object.keys(myObj).reduce((url, key) => {
const param = Array.isArray(myObj[key])
? myObj[key].join('-')
: myObj[key];
return [
url,
[key, encodeURIComponent(param)].join('=')
].join('&')
}, 'api/?conf');
console.log(myUrl);
这种方法使您能够在myObj
中具有任意数量的参数。
答案 2 :(得分:0)
您可以尝试以下方法:
let myObj = {
val1: 'someVal1',
val2: 'someVal2',
val3: [10, 39]
}
let myUrl = `api/?conf&val1=${myObj["val1"]}&val2=${myObj["val2"]}&val3=${myObj["val3"].join("-")}&some_other_data`
答案 3 :(得分:0)
您可以使用Template Literals来计算反勾号中的表达式:
let myObj = {
val1: 'someVal1',
val2: 'someVal2',
val3: [10, 39]
};
let myUrl = `api/?conf&val1=${encodeURIComponent(myObj.val1)}&val2=${encodeURIComponent(myObj.val1)}&&val3=${encodeURIComponent(myObj.val3.join("-"))}&&some_other_data`;
console.log(myUrl);
答案 4 :(得分:0)
您可以使用URLSearchParams
。
Array.isArray()
检查value
是否为数组-
连接,并将键和连接的字符串值附加到searchParams
append
键和值searchParams
使用URLSearchParams.toString()
获取查询字符串
const searchParams = new URLSearchParams();
let myObj = {
val1: 'someVal1',
val2: 'someVal2',
val3: [10, 39]
}
Object.entries(myObj).forEach(([key, value]) => {
if(Array.isArray(value))
searchParams.append(key, value.join('-'))
else
searchParams.append(key, value)
})
console.log(searchParams.toString())