如何在angular2中设置Content-Type和Accept得到错误415 Unsupported Media Type

Posted

技术标签:

【中文标题】如何在angular2中设置Content-Type和Accept得到错误415 Unsupported Media Type【英文标题】:How to set Content-Type and Accept in angular2 getting error 415 Unsupported Media Type 【发布时间】:2016-06-10 11:22:14 【问题描述】:

angular2中如何设置Content-Type和Accept?

我正在尝试在标题中发送带有内容类型(应用程序/json)的后调用 但是由于某种原因它不发送,它总是发送文本/纯文本; charset=UTF-8 内容类型 当我尝试进行 REST 服务调用时,我收到 415 Unsupported Media Type。我想我需要正确设置类型和内容类型,因为它不是从代码中设置的 我是什么 我们下面的标头请求

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


      
    

【问题讨论】:

【参考方案1】:

对于 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)

【讨论】:

【参考方案2】:

首先,您使用了来自angular2/angular2 的错误导入,现在 angular2 处于测试阶段,因此几乎所有导入都已更改。读出所有进口清单的答案。

https://***.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://***.com/a/34758630/5043867

【讨论】:

【参考方案3】:

这是一种更简洁的方法,它写在 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 查询是必需的。

【讨论】:

相反,您可以使用我的答案,为什么当我们可以通过将它们绑定到单个字段(即RequestOptions)来发送单个值时发送它们 感谢 wli,但 res.json().datares.json() 这取决于从 API 返回数据的方式。可能对某人有帮助。

以上是关于如何在angular2中设置Content-Type和Accept得到错误415 Unsupported Media Type的主要内容,如果未能解决你的问题,请参考以下文章

如何在angular2中的数组中设置补丁值(更新嵌套值)?

如何在angular2(material2)中设置小吃店的持续时间

如何在angular2中设置Content-Type和Accept得到错误415 Unsupported Media Type

如何在 MD-selection-list Angular2 中设置检查元素的最大限制

在Angular2的选择列表中设置最初选择的项目

在Angular2 Dart中设置路由器和RouterLink的正确方法是啥