我正在研究如何使用HttpClient的get方法,但我不知道如何在get请求中传递数据。我只知道如何获取url。我的意思是我想这样做:
curl -X GET \
http://127.0.0.1:5000/get_nodes \
-H 'Content-Type: application/json' \
-H 'Postman-Token: 604243c2-f9da-4f71-b356-a8e31608b45d' \
-H 'cache-control: no-cache' \
-d '{
"username" : "jack_list",
"node_name" : "nodeToFind"
}'我想将上面显示的带有curl -d标志的json传递给我的请求。我在网上看到的所有示例都是这样做的:
this.http.get("url_of_api"),但是如果我需要将json传递到我的请求中呢?
发布于 2019-03-12 06:59:26
HttpClient设置:
在开始使用Angular中的HttpClient之前。您需要在AppModule中导入HttpClientModule。
import {NgModule} from '@angular/core';
import {AppComponent} from './app.component';
import {HttpClientModule} from "@angular/common/http";
import {BrowserModule} from "@angular/platform-browser";
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
],
bootstrap: [AppComponent],
})
export class AppModule {
}无论您想在何处使用HttpClient,都需要将其注入到constructor中
constructor(private http: HttpClient) {}
GET:
对于get方法,可能看起来像这样。在本例中,请求URL将如下所示的http://127.0.0.1:5000/get_nodes?username="jack_list"&nodename="nodeToFind"
const data = {
"username" : "jack_list",
"node_name" : "nodeToFind"
};
const httpOptions = {
params: data,
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Postman-Token': '604243c2-f9da-4f71-b356-a8e31608b45d',
'Cache-control': 'no-cache'
});
this.http.get('http://127.0.0.1:5000/get_nodes', httpOptions);帖子:
对于post,方法将非常类似,您只需在其中添加数据
const data = {
"username" : "jack_list",
"node_name" : "nodeToFind"
};
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Postman-Token': '604243c2-f9da-4f71-b356-a8e31608b45d',
'Cache-control': 'no-cache'
});
this.http.post('http://127.0.0.1:5000/get_nodes', data, httpOptions);发布于 2019-03-12 06:41:10
GET请求通常不包含请求正文。您必须将它们编码到URL中。
例如:
请求data的JSON表示:
{
"baz": "qux",
"wotsit": [
1,2,'three',
]
}等价的GET请求:
GET /foo/bar?baz=qux&wotsit[]=1&wotsit[]=2&wotsit[]=three我有一个implemented a helper function in my answer here,它将复杂的对象编码成一系列的GET参数。
发布于 2019-03-12 06:58:01
高级HttpClient.get()不提供请求主体参数,因为包含主体的GET是非标准的,您应该能够使用HttpClient.request()。注意:您可能还需要在尚未测试的JSON.stringify()中包装data。
const data = {
"username": "jack_list",
"node_name": "nodeToFind"
};
const headers = new HttpHeaders();
headers.set('Content-Type', 'application/json ');
headers.set('Postman-Token', '604243c2-f9da-4f71-b356-a8e31608b45d');
headers.set('cache-control', 'no-cache');
const req = new HttpRequest('GET', 'http://127.0.0.1:5000/get_nodes', data, { headers });
this.http.request(req).subscribe(res => {
// do with res
});更新:
看来浏览器不会让你这么做的。
async GET request with body from browser https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET
所以我的最新答案是这是不可能的。
https://stackoverflow.com/questions/55111458
复制相似问题