最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - With the Node URL module, how do you set all search params at once? - Stack Overflow

programmeradmin0浏览0评论

I see that you can do:

myUrl.searchParams.set('param1', 'value');
myUrl.searchParams.set('param2', 'value');
...

What I would like to do is more like:

myUrl.searchParams.set({
    param1: 'value',
    param2: 'value
});

But this does not work.

I see in the docs that you can use the URLSearchParams class to do this:

myParams = new URLSearchParams({
    param1: 'value',
    param2: 'value
});

But what I can not figure out is how to use it. These do not work:

myUrl.searchParams = myParams;

or

myUrl.searchParams.set(myParams);

Nor did a few other things that I've tried. Unless I'm just going crazy, I can not find where it shows how to do this in the docs.

I see that you can do:

myUrl.searchParams.set('param1', 'value');
myUrl.searchParams.set('param2', 'value');
...

What I would like to do is more like:

myUrl.searchParams.set({
    param1: 'value',
    param2: 'value
});

But this does not work.

I see in the docs that you can use the URLSearchParams class to do this:

myParams = new URLSearchParams({
    param1: 'value',
    param2: 'value
});

But what I can not figure out is how to use it. These do not work:

myUrl.searchParams = myParams;

or

myUrl.searchParams.set(myParams);

Nor did a few other things that I've tried. Unless I'm just going crazy, I can not find where it shows how to do this in the docs.

Share Improve this question asked Oct 31, 2017 at 2:01 KenmoreKenmore 1,5953 gold badges16 silver badges41 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 20

You had the right thought, and it's not a typo, but you need to assign the params object to search instead of searchParams.

myUrl.search = myParams

The myURL.searchParams object is an instance of URLSearchParams created automatically by new URL(). You can use its methods, but... sadly, once that object is created, it is too late to set multiple params at once, because only the constructor supports that and none of its methods do.

It is logical to think that you should be able to create a new instance yourself and assign it to the searchParams property. But they decided to make that property read-only. I think this is going to confuse a lot of people, it's needlessly unintuitive.

The good news is, myParams.search is writable and it will happily serialize the myParams object.

const myUrl = new URL('https://example.com/');
myUrl.search = new URLSearchParams({
    param1 : 'value',
    param2 : 'value'
});
myUrl.toString();
// https://example.com/?param1=value&param2=value

I hope someone champions the ability to pass an object to myParams#set() and that one day we can have just one search related property on URLs.

发布评论

评论列表(0)

  1. 暂无评论