Search code examples
angularhttpclient

How can I make GET request with an array


let owners = ['Chris', 'John'];

this.http.get('/pets', {'owners': owners}).subscribe(...);

The request goes like .../pets/owners=Chris&owners=John

But I want to request like .../pets/owners=['Chris', 'John'].

Are there any ways to achieve this?


Solution

  • I'm just curious as to why is your API is expecting you to send the request something like this?

    This data that you're sending should be either sent as a request payload to a POST request. Something like this:

    let owners = ['Chris', 'John'];
    this.http.post(`/pets/owners`, { owners }).subscribe(...);
    

    Or you should send it as a GET request but then as query params in that case:

    let owners = ['Chris', 'John'];
    this.http.get(`/pets?owners=${owners.toString()}`).subscribe(...);
    

    If you still are sending the data like this, how exactly is your server intercepting this request? Why I'm asking that is because you are not setting the owners array as a value to anything.

    If you still want to sent it like this, here's how you'd do that:

    let owners = ['Chris', 'John'];
    this.http.get(`/pets/owners=${JSON.stringify(owners)}`).subscribe(...);
    

    But then again, I'm not really sure how your backend is making sense of this request.