簡體   English   中英

如何設置內容類型和接受角度2獲取錯誤415不支持的媒體類型

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

如何在angular2中設置Content-Type和Accept?

我試圖在標題中發送內容類型(application / json)的帖子調用但是因為某些原因它不發送,它總是發送text / plain; charset =內容類型中的UTF-8當我嘗試進行REST服務調用時,我得到415不支持的媒體類型。 我認為我需要正確地設置類型和內容類型它不會從代碼設置我在我們下面的標頭請求

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

代碼如下

    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('/');
          });


      }
    }

這是一種更清晰的方式,它是用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)

請注意,我認為只有POST查詢才需要這樣做。

首先你使用的是來自angular2/angular2不正確的導入,現在angular2現在處於測試階段,因此幾乎所有的導入都已被更改。 讀出所有進口清單的答案。

https://stackoverflow.com/a/34440018/5043867

然后根據我的理解你想使用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() }]
                }
            });
}

我假設使用PostRequest作為方法名稱的虛擬示例。 有關HTTP和REST API調用的更多詳細信息,請參閱此處: https//stackoverflow.com/a/34758630/5043867

對於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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM