如何在 Angular 2 中发布 JSON?

新手上路,请多包涵

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

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

当我尝试这个时,请求正文如下所示:

在此处输入图像描述

因此,它不发送实际的 json,而是发送“[object Object]”。而不是“请求有效负载”,它应该是“JSON”。我究竟做错了什么?

原文由 Sebastian Olsen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 508
2 个回答

您需要对有效负载进行字符串化

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

原文由 Ankit Singh 发布,翻译遵循 CC BY-SA 3.0 许可协议

我一直在寻找在 Angular 中发布 json 数据的问题的视觉答案,但无济于事。现在我终于有了一些工作,让我们分享一下:

内联

假设您期望 T 类型的 json 响应正文。

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

官方文档

可扩展类

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

export class MyHttpService {
  constructor(protected http: HttpClient) {}

  headers = new HttpHeaders({
    'Content-Type': 'application/json'
  });

  postJson<T>(url: string, data: any): Observable<T> {
    return this.http.post<T>(
      url,
      JSON.stringify(data),
      {headers: this.headers}
    )
  }

要点

一开始我错过了这种传递内容类型的“嵌套”方式:

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

原文由 Arnaud P 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进