简体   繁体   中英

How to send a HTTP POST REQUEST by parameters using typescript

I would like to send a POST request by param similar to that:

http://127.0.0.1:9000/api?command={"command":"value","params":{"key":"value","key":"value","key":"value","key":value,}}

I tried to do that, but not working:

    let command: HttpParams = new HttpParams();
    let params: HttpParams = new HttpParams();

    command = command.append('command', 'value');

    params = params.append('key', value);
    params = params.append('key', value);
    params = params.append('key', value);
    params = params.append('key', value);
    command = command.append('params', params.toString());


    this.httpClient.post('/api?', null, {
        params: command
    });


The error is: 500 (Internal Server Error)

Could you please help me?

The code 500 given by the server has the following description:

The HyperText Transfer Protocol (HTTP) 500 Internal Server Error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.

I think your server is trying to process your request. So remove ".toString()" in your code.

command = command.append('params', params.toString());

Then try (Ctrl + shift + Supr) to see chrome dev tools, and go to the Networks tab. You will see all your calls. Check if your request has the format as you want.

The solution is:

1) First I create the object containing the command info and parameters. Similar to that:

const object = {
  command: 'command description',
  params: {
    properti: value,
    properti: value,
    properti: value,
  }
};

2) After, I convert this object to json using JSON.stringify():

// convert object to json data
const jsonData = JSON.stringify(object);

3) After second step, I encapsulate the json data in HttpParams

// encapsulate json data in http param
let httpParams: HttpParams = new HttpParams();
httpParams = httpParams.append('command', automationTestTriggerJson);

4) and finally, I send POST by param using httpClient. Similar to that:

this.httpClient.post<T>(url, body, {
        httpParams: parameters
});

NOTE: I don't know if it's is a better solution bur it's working for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM