gpt4 book ai didi

Angular http获取数据

转载 作者:可可西里 更新时间:2023-11-01 16:39:59 27 4
gpt4 key购买 nike

我正在查看如何使用 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"
}'

我想将 json 传递给我的请求,如上所示,带有 curl -d 标志。我在网上看到的所有示例都只是这样做:

this.http.get("url_of_api"),但是如果我需要将 json 传递到我的请求中怎么办?

最佳答案

HttpClient 设置:

在开始使用 Angular 中的 HttpClient 之前。您需要将 HttpClientModule 导入您的 AppModule

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的地方你都需要将它注入(inject)constructor

构造函数(私有(private) http: HttpClient){}

获取:

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);

关于 Angular http获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55111458/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com