我试图使用POST请求从服务获取数据.但我不能改变标题(TS不会编译)或内容类型.我在控制台中收到此错误:
status”:415,”error”:”Unsupported Media Type”,”exception”:”org.springframework.web.HttpMediaTypeNotSupportedException”,”message”:”Content type ‘text/plain’ not supported”
下面是我的组件代码.
import { Component,OnInit } from '@angular/core'; import { Http,Headers,Response,URLSearchParams } from '@angular/http'; import { HttpClient } from '@angular/common/http'; import 'rxjs/add/operator/map'; @Component({ selector: 'app-search',templateUrl: './search.component.html',styleUrls: ['./search.component.css'] }) export class SearchComponent implements OnInit { searchValue: any = ''; constructor(private http: HttpClient) { } getData() { this.http.post('MY URL',JSON.stringify({ "q": "Achmea" })) .subscribe( data => { alert('ok'); console.log(data); } )
注意:使用了代码段,因为格式化不会让我发布为pre.
使用最新的角度4版本.
还应正确配置服务器,仅接受json数据.
我尝试了Angular文档中的示例,但没有一个工作.
任何人都知道如何让它工作?
提前致谢.
解决方法
在您的示例中(以及在注释中),由angular提供的两个不同的http实现被混合.由于’@ angular / common / http’的角度4 HttpClient可用,因此是推荐的方法.由于角度为5,来自’@ angular / http’的旧Http甚至被标记为已弃用.
为了防止来自后端的异常消息,您必须按以下方式设置标头:
const headers = new HttpHeaders().set('Content-Type','application/json; charset=utf-8'); return this.httpClient.post<T>(this.httpUtilService.prepareUrlForRequest(url),body,{headers: headers}) ...