角http发布请求内容类型从'text/plain'到'application/json' [英] Angular http post request content type from 'text/plain' to 'application/json'
问题描述
我正在尝试使用POST请求从服务获取数据.但是我无法更改标头(TS无法编译)或内容类型.我在控制台中收到此错误:
Im trying to get data from a service using POST request. But I cant change the headers (TS wont compile) or content type. I get this error in console:
状态":415,错误":不支持的媒体类型",例外":"org.springframework.web.HttpMediaTypeNotSupportedException",消息":内容类型'text/plain'不支持"
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身份发布.
NB: Used the code snippet because the formatting wouldnt let me post as pre.
使用最新的angular 4版本.服务器也应该正确配置,仅接受json数据.我尝试了Angular文档中的示例,但没有一个起作用.
Using latest angular 4 version. Also server should be correctly configured, accepting only json data. I tried the examples from Angular docs but none of them worked.
任何人都知道如何使它正常工作吗?预先感谢.
Anyone have any idea how to get it working?? Thanks in advance.
推荐答案
在您的示例(以及注释中)中,由angular提供的两个不同的http实现混在一起.由于来自'@ angular/common/http'的angular 4 HttpClient是可用的,因此是推荐的方法.自从angular 5起,来自'@ angular/http'的旧Http甚至被标记为已弃用.
In your example (and also in the comments) the two different http implementations which are provided by angular are mixed up. Since angular 4 HttpClient from '@angular/common/http' is available and is the recommended way to go. Since angular 5 the older Http from '@angular/http' is even marked as deprecated.
为了防止您的后端收到异常消息,您必须通过以下方式设置标头:
In order to prevent the exception message from your backend you have to set your headers in the following way:
const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
return this.httpClient.post<T>(this.httpUtilService.prepareUrlForRequest(url), body, {headers: headers})
...
请从代码中的"@ angular/http"中删除所有依赖项.只要您使用此模块中的对象,您的代码就会出现问题.
Please remove all dependencies from '@angular/http' in your code. As long as you are using objects from this modul you will have issues with your code.
这篇关于角http发布请求内容类型从'text/plain'到'application/json'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!