angularangular-http

Angular 2 http post params and body


I'm trying to do an API call from my angular app. What I want to do is send a post request to the API with a command param. I have done a lot of server-side testing as well as going through the outgoing request, and the $_POST nor body data is never there. I am therefore pretty sure that the problem lays within this piece of code.

public post(cmd: string, data: object): Observable<any> {
    const params = new URLSearchParams();
    params.set('cmd', cmd);
    
    const options = new RequestOptions({
      headers: this.getAuthorizedHeaders(),
      responseType: ResponseContentType.Json,
      params: params,
      body: data,
      withCredentials: false
    });
    
    console.log('Options: ' + JSON.stringify(options));
    
    return this.http.post('http://t2w.dev/index.php', data, options)
      .map(this.handleData)
      .catch(this.handleError);
}

I have tried many different JSON structures as data but this is the core of what I am trying to send:

{
    "Username": "No thanks",
    "Password": "Donno"
}

this.handleData and this.handleError is a method taking data and error as arguments, and returns just what I want.

The API is setup to log anything coming through $_POST which works fine when running requests from anywhere but my angular app. What I have done so far:

  1. Passing raw query instead of URLSearchParams.
  2. Passing the request without body.
  3. Passing all values in RequestOptions.
  4. Passing params as a string.
  5. Passing body as params.
  6. Passing body as JSON.stringify({ "Username": "No thanks", "Password": "Donno" }

Console output of RequestOptions

Options: {"method":null,"headers":{"Content-Type":["application/json"],"Accept":["application/json"],"X-CLIENT-ID":["380954038"],"X-CLIENT-SECRET":["5BgqRO9BMZ4iocAXYjjnCjnO7fHGN59WP8BTRZ5f"]},"body":"{}","url":null,"params":{"rawParams":"","queryEncoder":{},"paramsMap":{}},"withCredentials":false,"responseType":1} VM8529:1 XHR finished loading: POST "http://t2w.dev/index.php".

Does anyone have any clue why the data never gets sent?


Solution

  • And it works, thanks @trichetriche. The problem was in my RequestOptions, apparently, you can not pass params or body to the RequestOptions while using the post. Removing one of them gives me an error, removing both and it works. Still no final solution to my problem, but I now have something to work with. Final working code.

    public post(cmd: string, data: string): Observable<any> {
    
        const options = new RequestOptions({
          headers: this.getAuthorizedHeaders(),
          responseType: ResponseContentType.Json,
          withCredentials: false
        });
    
        console.log('Options: ' + JSON.stringify(options));
    
        return this.http.post(this.BASE_URL, JSON.stringify({
          cmd: cmd,
          data: data}), options)
          .map(this.handleData)
          .catch(this.handleError);
      }