0

I have to pass query params to a post request in angular4 so i used HttpParams from angular 4 . This works fine with other post request but fails while accessing the authentication token from the backend. This is how the query params should look like

grant_type=password&username=username&password=password

so i tried like this

login(username: string, password: string) {
    const headers = new HttpHeaders()
      .set('Content-Type', 'application/x-www-form-urlencoded')
      .set('Accept', 'application/json');
      let params = new HttpParams();
      params = params.set('username', username);
      params = params.set('password', password);
      params = params.set('grant_type', 'password');
    return this.http.post('////////////', {params: params},
      { headers: headers }).subscribe(data => {
      console.log(data);
    },
    err => {
      console.log('Error occured');
    });
  }
5
  • 1
    please don't send passwords in a query string. They are logged in countless insecure locations between the browser and the server. Commented Nov 22, 2017 at 18:08
  • what do you mean? Commented Nov 22, 2017 at 18:18
  • when you send an http request, the url, including the query string, is logged in several locations between the browser and the server, and most servers log their requests too. These logs are not secure, and shouldn't contain plain text usernames and passwords. This is why they're sent in the post body, which is never logged. Commented Nov 22, 2017 at 18:19
  • @bryan60 the OP is not passing the params in the query string. The params are sent, as JSON, in the request body. Commented Nov 22, 2017 at 18:20
  • the title reads "sending url query params in angular 4 doesn't work" and the code supports that this is what they're trying to accomplish, which is why I'm trying to advise against doing this, if I'm misreading, then my bad. Commented Nov 22, 2017 at 18:21

1 Answer 1

1

You're passing your parameters as part of a JSON object containing a single key named params, whose value is the query string that should be the body itself.

It should be

return this.http.post(url, params.toString(), { headers })

Everything would be easier if your backend accepted JSON rather than x-www-form-urlencoded.

Sign up to request clarification or add additional context in comments.

3 Comments

ok. so if i understand correctly. if the backend accepts x-www-form-urlencoded then i have to use params.toString(). right???
If it's x-www-form-urlencoded, you need to send, in the body of the request, a string that is in the x-www-form-urlencoded format.
May be you could answer my new question stackoverflow.com/questions/47457879/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.