[英]How to send a HTTP POST REQUEST by parameters using typescript
I would like to send a POST request by param similar to that:我想通过类似的 param 发送一个 POST 请求:
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:服务端给出的代码500有如下描述:
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.
超文本传输协议 (HTTP) 500 内部服务器错误服务器错误响应代码表示服务器遇到了阻止其完成请求的意外情况。
I think your server is trying to process your request.我认为您的服务器正在尝试处理您的请求。 So remove ".toString()" in your code.
所以在你的代码中删除“.toString()”。
command = command.append('params', params.toString());
Then try (Ctrl + shift + Supr) to see chrome dev tools, and go to the Networks tab.然后尝试 (Ctrl + shift + Supr) 查看 chrome 开发工具,然后转到“网络”选项卡。 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. 1) 首先我创建包含命令信息和参数的对象。 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(): 2) 之后,我使用 JSON.stringify() 将此对象转换为 json:
// convert object to json data
const jsonData = JSON.stringify(object);
3) After second step, I encapsulate the json data in HttpParams 3)第二步之后,我将json数据封装在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. 4)最后,我使用httpClient通过参数发送POST。 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.注意:我不知道这是否是更好的解决方案,但它对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.