Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Content-Type and Accept in angular2 getting error 415 Unsupported Media Type

How to set Content-Type and Accept in angular2?

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; charset=UTF-8 in content type I am getting 415 Unsupported Media Type when I try to make a REST service call. 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('/');           });         }     } 
like image 997
bonjour Avatar asked Feb 27 '16 03:02

bonjour


People also ask

How do I fix 415 unsupported media type?

Fixing 415 Unsupported Media Type errorsEnsure that you are sending the proper Content-Type header value. Verify that your server is able to process the value defined in the Content-Type header. Check the Accept header to verify what the server is actually willing to process.

Why do we get 415 error?

The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format. The format problem might be due to the request's indicated Content-Type or Content-Encoding , or as a result of inspecting the data directly.


2 Answers

Here's a cleaner way, which is written in the Angular2 docs (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.

like image 177
wli Avatar answered Oct 27 '22 16:10

wli


First of all you are using incorrect imports from angular2/angular2 now angular2 is in beta now so almost all imports have been changed. Read out this answer for all list of imports.

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.

 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. for more details regarding HTTP and REST API call refer here: https://stackoverflow.com/a/34758630/5043867

like image 27
Pardeep Jain Avatar answered Oct 27 '22 15:10

Pardeep Jain