如何在Angular 2中POST JSON数据?

11 浏览
0 Comments

如何在Angular 2中POST JSON数据?

当我尝试获取json时,我不明白我做错了什么,我的服务器返回“undefined”。

POST(url, data) {
        var headers = new Headers(), authtoken = localStorage.getItem('authtoken');
        headers.append("Content-Type", 'application/json');
        if (authtoken) {
        headers.append("Authorization", 'Token ' + authtoken)
        }
        headers.append("Accept", 'application/json');
        var requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: this.apiURL + url,
            headers: headers,
            body: data
        })
        return this.http.request(new Request(requestoptions))
        .map((res: Response) => {
            if (res) {
                return { status: res.status, json: res.json() }
            }
        });
    }

以及我的函数:

login(username, password) {
        this.POST('login/', {test: 'test'}).subscribe(data => {
            console.log(data)
        })
    }

当我尝试这样做时,请求体如下所示:

enter image description here

所以它不是发送实际的json,而是发送“[object Object]”。

而不是“Request payload”,它应该是“JSON”。我做错了什么?

0
0 Comments

如何在Angular 2中POST JSON数据?

问题出现的原因是作者在寻找关于在Angular中POST JSON数据的可视化解答很长一段时间,但没有找到。最终作者找到了一种可行的方法,并决定分享出来。

解决方法如下:

第一种方法是直接内联代码。假设你期望得到一个类型为T的JSON响应体。使用以下代码:

const options = {headers: {'Content-Type': 'application/json'}};
this.http.post(url, JSON.stringify(data), options).subscribe(
    (t: T) => console.info(JSON.stringify(t))
);

官方文档参考链接:官方文档

第二种方法是创建一个可扩展的类。首先导入必要的模块:

import { HttpClient, HttpHeaders } from '/common/http';

然后创建一个名为MyHttpService的类:

export class MyHttpService {
  constructor(protected http: HttpClient) {}
  headers = new HttpHeaders({
    'Content-Type': 'application/json'
  });
  postJson(url: string, data: any): Observable {
    return this.http.post(
      url,
      JSON.stringify(data),
      {headers: this.headers}
    )
  }
}

最后,作者提到在开始时他错过了一种传递content-type的嵌套方式:

{headers:{'Content-Type': 'application/json'}}

通过以上方法,你可以在Angular 2中POST JSON数据。

0
0 Comments

问题:如何在Angular 2中POST JSON数据?

解决方法:确保请求头中的Content-Type设置为application/json,同时将请求体中的数据使用JSON.stringify()方法进行转换。

具体代码如下:

import { HttpClient, HttpHeaders } from '@angular/common/http';
// 创建请求头
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
};
// 定义数据
const data = {
  key1: 'value1',
  key2: 'value2'
};
// 发送POST请求
this.http.post(url, JSON.stringify(data), httpOptions)
  .subscribe(response => {
    console.log(response);
  });

请注意,以上代码中的`this.http`是一个HttpClient实例,需要在Angular模块中进行依赖注入。

希望这个解决方法对你有帮助!

0
0 Comments

问题的原因是在Angular 2中如何将JSON数据进行POST请求。解决方法是使用JSON.stringify()方法将数据转换为字符串。

首先,我们需要创建一个RequestOptions对象,并指定请求的方法为POST,URL为this.apiURL + url,headers为headers,body为JSON.stringify(data)。这里的data是要发送的JSON数据。

代码如下:

var requestoptions = new RequestOptions({
    method: RequestMethod.Post,
    url: this.apiURL + url,
    headers: headers,
    body: JSON.stringify(data)
});

接下来,我们需要将data转换为字符串。这可以通过使用JSON.stringify()方法来实现。JSON.stringify()方法将一个JavaScript对象或值转换为一个JSON字符串。

代码如下:

JSON.stringify(data)

如果我们要将ECMAScript 6中的Map对象转换为字符串,我们可以使用Map对象的内置方法。但是,由于Map对象不是原生的JSON对象,所以不能直接使用JSON.stringify()方法进行转换。

为了解决这个问题,我们可以参考一个Stack Overflow上的答案,链接为http://stackoverflow.com/questions/29085197。

通过查看这个链接,我们可以找到一个解决方案来将ECMAScript 6中的Map对象转换为字符串。

整体而言,解决方法就是使用JSON.stringify()方法将数据转换为字符串,以便在Angular 2中进行POST请求。如果我们要将ECMAScript 6中的Map对象转换为字符串,可以参考上述提供的链接。

0