-2

When I try to construct a url in JavaScript using new URL(url, base), it strips the pathname in base

below is my code

const getUrl = () => {
  const ids = ["1","2","3"];
  const url = new URL("/items", "https://example.com/v1");
  url.searchParams.set("id", ids?.toString() ?? "");
  
  return url.toString();
};

console.log(getUrl());
// https://example.com/items?id=1%2C2%2C3

I need the output to be: https://example.com/v1/items?id=1%2C2%2C3

0stone0
  • 34,288
  • 4
  • 39
  • 64
Rahul Yadav
  • 2,627
  • 5
  • 30
  • 52
  • 1
    Does this answer your question? [How to build query string with Javascript](https://stackoverflow.com/questions/316781/how-to-build-query-string-with-javascript) – Liam Jun 05 '23 at 13:10
  • No, I have already solved the query string part of the problem – Rahul Yadav Jun 05 '23 at 13:12
  • 2
    The behavior you're describing is just how [the API works](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL#examples). – Maximilian Burszley Jun 05 '23 at 13:12
  • If you want `["1","2","3"]` url encoded then you'll need to do that separately. this is a completely non standard way of sending arrays in a query string. So you'll have to write that yourself. I'd suggest you actually use a POST and JSON encoding, not this. Querystring is only for simple key value pairs not objects or arrays. – Liam Jun 05 '23 at 13:12
  • A leading slash in a relative URL _always_ refers to the domain root. You would actually need `new URL("items", "https://example.com/v1/")` here. – CBroe Jun 05 '23 at 13:14
  • `v1` is part of the `url`, use :`new URL("/v1/items", "https://example.com/");` – 0stone0 Jun 05 '23 at 13:16

1 Answers1

0

Instead of using

const url = new URL("/items", "https://example.com/v1");

You can use

const url = new URL("https://example.com/v1"+"/items");

const url = new URL(path, base)

here base will ignore all the sub path, and it will construct your URL by using only the base path ie domain (https://example.com)