Cómo configurar Content-Type y Accept en angular2 getting error 415 Tipo de medio no compatible
¿Cómo configurar Content-Type y Accept en angular2?
Estoy tratando de enviar una llamada post con el tipo de contenido (aplicación / json) en el encabezado Pero para alguna razón no envía, siempre envía text / plain; charset = UTF-8 en el tipo de contenido Estoy recibiendo 415 Tipo de medio no compatible cuando intento hacer una llamada de servicio REST. Creo que necesito establecer el tipo y el tipo de contenido correctamente de alguna manera no se establece desde el código lo que yo fo Debajo de nosotros la solicitud de encabezado
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
El Código es abajo
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('/');
});
}
}
3 answers
Aquí hay una forma más limpia, que está escrita en los documentos 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)
Tenga en cuenta que creo que esto solo es necesario para las consultas POST.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-16 23:19:16
En primer lugar, está utilizando importaciones incorrectas de angular2/angular2
ahora angular2 está en beta, por lo que casi todas las importaciones se han cambiado. Lea esta respuesta para ver toda la lista de importaciones.
Https://stackoverflow.com/a/34440018/5043867
Luego, hasta mi entendimiento, desea llamar a Post request usando REST Api Creo que y desea enviar content type='application/json'
por lo que tiene que enviar lo mismo agregándolo a Header
Posteo el ejemplo de usar encabezado para usar tipo de contenido como debajo.
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() }]
}
});
}
Estoy asumiendo un ejemplo ficticio usando PostRequest
como nombre del método. para obtener más detalles sobre la llamada a la API HTTP y REST, consulte aquí:
https://stackoverflow.com/a/34758630/5043867
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-15 09:00:20
Para la versión 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)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-30 08:15:55