[英]How to set Content-Type and Accept in angular2 getting error 415 Unsupported Media Type
How to set Content-Type and Accept in angular2? 如何在angular2中设置Content-Type和Accept?
I am trying to send post call with content type(application/json) in header But for somereason it does not send, it always send text/plain; 我试图在标题中发送内容类型(application / json)的帖子调用但是因为某些原因它不发送,它总是发送text / plain; charset=UTF-8 in content type I am getting 415 Unsupported Media Type when I try to make a REST service call.
charset =内容类型中的UTF-8当我尝试进行REST服务调用时,我得到415不支持的媒体类型。 I think i need to set the type and Content-type properly somehow it does not set from code what i fo Below us the header request
我认为我需要正确地设置类型和内容类型它不会从代码设置我在我们下面的标头请求
Accept
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Content-Length
13
Content-Type
text/plain; charset=UTF-8
Host
enrova.debug-zone.com:8000
Origin
http://localhost:8000
Referer
http://localhost:8000/add
User-Agent
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Code is below 代码如下
import {Component, View} from 'angular2/angular2';
import { Inject} from 'angular2/di';
import {Http} from 'angular2/http';
export class AchievementsService {
constructor( @Inject(Http) private http: Http) {
}
getAchievementsOfType(type: string) : any {
var path = '/api/achievements/' + type;
return this.http.get(path);
}
getAllAchievements() : any {
var path = '/api/achievements';
return this.http.get(path);
}
addAnAchievement(newAchievement) {
//var path = '/api/achievements';
var path = 'http://test.com:8000/branch';
return this.http.post('http://test.com:8000/branch', JSON.stringify(newAchievement),{
headers: { 'Content-Type': 'application/json; charset=utf-8'} });
}
**Calling Class**
import {Component, View} from 'angular2/angular2';
import { _settings } from '../../settings'
import {FormBuilder, Validators, formDirectives, ControlGroup} from 'angular2/forms';
import {Inject} from 'angular2/di';
import {Router} from 'angular2/router';
import {AchievementsService} from '../../services/achievementsService';
@Component({
selector: 'add',
injectables: [FormBuilder]
})
@View({
templateUrl: _settings.buildPath + '/components/add/add.html',
directives: [formDirectives]
})
export class Add {
addAchievementForm: any;
constructor( @Inject(FormBuilder) private formBuilder: FormBuilder,
@Inject(Router) private router: Router,
@Inject(AchievementsService) private achievementsService: AchievementsService) {
this.addAchievementForm = formBuilder.group({
name: ['']
});
}
// This is the funtion that call post call written in achievementsService.ts
addAchievement() {
this.achievementsService.addAnAchievement(this.addAchievementForm.value)
.map(r => r.json())
.subscribe(result => {
this.router.parent.navigate('/');
});
}
}
Here's a cleaner way, which is written in the Angular2 docs ( https://angular.io/docs/ts/latest/guide/server-communication.html ). 这是一种更清晰的方式,它是用Angular2文档( https://angular.io/docs/ts/latest/guide/server-communication.html )编写的。
import {Headers, RequestOptions} from 'angular2/http';
let body = JSON.stringify({ 'foo': 'bar' });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(url, body, options)
.map(res => res.json().data)
.catch(this.handleError)
Note that I believe this is only required for POST queries. 请注意,我认为只有POST查询才需要这样做。
First of all you are using incorrect imports from angular2/angular2
now angular2 is in beta now so almost all imports have been changed. 首先你使用的是来自
angular2/angular2
不正确的导入,现在angular2现在处于测试阶段,因此几乎所有的导入都已被更改。 Read out this answer for all list of imports. 读出所有进口清单的答案。
https://stackoverflow.com/a/34440018/5043867 https://stackoverflow.com/a/34440018/5043867
then up to my understanding you want to call Post request using REST Api I think and you want to send content type='application/json'
so you have to send the same by appending it to Header
I post the example of using header to use content type like below. 然后根据我的理解你想使用REST Api调用Post请求我认为你要发送
content type='application/json'
所以你必须通过将它附加到Header
发送相同的帖子我发布使用标头的例子来使用内容类型如下。
import {Component, View, Inject} from 'angular2/core';
import {Http} from 'angular2/http';
PostRequest(url,data) {
this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'))
this.requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: this.headers,
body: JSON.stringify(data)
})
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
return [{ status: res.status, json: res.json() }]
}
});
}
I'm assuming dummy example using PostRequest
as method name. 我假设使用
PostRequest
作为方法名称的虚拟示例。 for more details regarding HTTP and REST API call refer here: https://stackoverflow.com/a/34758630/5043867 有关HTTP和REST API调用的更多详细信息,请参阅此处: https : //stackoverflow.com/a/34758630/5043867
For Angular 5.2.9 version 对于Angular 5.2.9版本
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
return this.http.post(url, body, httpOptions)
.map(res => res.json().data)
.catch(this.handleError)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.