【问题标题】:Angular post call not working (Getting 415 error)Angular post 调用不起作用(出现 415 错误)
【发布时间】:2022-11-30 23:57:32
【问题描述】:

我正在尝试从以下代码中获取响应。这给出了 JSON 输出。在服务器中,我收到415 问题并且响应也没有到来。

 constructor(private http: HttpClient){}

 public getReports(postData: IRreq) {

    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');

    return this.http.post(sampleurl, JSON.stringify(postData), { headers: headers })    
    .pipe(map((res:any) => this.report = res));

};

API 没有问题,在邮递员中获得 200 和响应。不确定这里的问题是什么,需要一些帮助。谢谢

【问题讨论】:

  • 415 代表Unsupported Media Type。您是否也在 Postman 中以 application/json 的形式发送有效负载?在任何情况下,您的 api 都会故意返回 415?没有更多信息,我没有其他想法
  • 删除 JSON.stringify 可以修复它

标签: javascript angular http http-headers angular-httpclient


【解决方案1】:

您正在使用 Angular 2 的示例。那时 json 内容类型不是标准方式。

现在,当您想要使用 json 内容类型发出请求时,您只需执行以下操作:

const body = { title: "Angular PUT Request Example" };
this.http
  .put<any>("https://jsonplaceholder.typicode.com/posts/1", body)
  .subscribe((data) => console.warn(data));

所以你不需要对 json 编码等做任何魔法。

【讨论】:

    猜你喜欢
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2020-04-18
    • 2020-10-08
    • 1970-01-01
    • 2021-10-16
    相关资源
    最近更新 更多