如何设置Content-Type和在angular2得到错误415不支持的媒体类型接受 [英] How to set Content-Type and Accept in angular2 getting error 415 Unsupported Media Type

查看:958
本文介绍了如何设置Content-Type和在angular2得到错误415不支持的媒体类型接受的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置Content-Type和在angular2接受?

我要发送的呼叫后,在头的内容类型(应用/ JSON)
但对于somereason它不发送,它总是发送text / plain的;字符集=在内容类型UTF-8
我得到415不支持的媒体类型,当我尝试做一个REST服务调用。我想我需要设置正确不知它不会从code设置的类型和内容类型
我FO
下面我们头要求

 接受
text / html的,是application / xhtml + xml的,应用/ XML; Q = 0.9 * / *; Q = 0.8
接受编码
gzip的,放气
接受语言
EN-US,EN; Q = 0.5
内容长度
13
内容类型
text / plain的;字符集= UTF-8
主办
enrova.debug-zone.com:8000
起源
HTTP://本地主机:8000
引用者
HTTP://本地主机:8000 /加
用户代理
Mozilla的/ 5.0(Windows NT的10.0; WOW64; RV:39.0)的Gecko / 20100101火狐/ 39.0

code低于

 进口{组件,查看}从'angular2 / angular2';
    进口{}注入从'angular2 / DI';
    从angular2 / HTTP'进口{}的Http;    出口类AchievementsService {
        构造函数(@注入(HTTP)私人HTTP:HTTP){
        }        getAchievementsOfType(类型:字符串):任何{
            VAR路径='/ API /业绩/'+型;
            返回this.http.get(路径);
        }        getAllAchievements(){任何
            VAR路径='/ API /成就';
            返回this.http.get(路径);
        }        addAnAchievement(newAchievement){            // VAR路径='/ API /成就';
            VAR路径='http://test.com:8000/branch';
            返回this.http.post('http://test.com:8000/branch',JSON.stringify(newAchievement){
            标题:{内容类型:应用/ JSON的;字符集= utf-8'}});    }**调用类**
 进口{组件,查看}从'angular2 / angular2';
    进口{} _settings从'../../settings
    进口{FormBuilder,验证,formDirectives,ControlGroup}从'angular2 /表格;
    进口{}注入从'angular2 / DI';
    进口{}路由器从'angular2 /路由器;
    进口{} AchievementsService从'../../services/achievementsService';    @零件({
      选择:添加,
      注射:[FormBuilder]
    })
    @视图({
      templateUrl:_settings.buildPath +'/components/add/add.html',
      指令:[formDirectives]
    })
    出口类添加{
      addAchievementForm:任;      构造函数(@注入(FormBuilder)私人formBuilder:FormBuilder,
        @Inject(路由器)私人路由器:路由器,
        @Inject(AchievementsService)私人achievementsService:AchievementsService){        this.addAchievementForm = formBuilder.group({
            名称: ['']        });
      }
    //这是拨打电话后写在achievementsService.ts的funtion
      addAchievement(){
        this.achievementsService.addAnAchievement(this.addAchievementForm.value)
          .MAP(R => r.json())
          .subscribe(结果=> {
            this.router.parent.navigate('/');
          });
      }
    }


解决方案

下面是一个更清洁的方式,这是写在Angular2文档(的 https://angular.io/docs/ts/latest/guide/server-communication.html )。

 进口{接头,RequestOptions}从'angular2 / HTTP';让身体= JSON.stringify({'富':'棒'});
让标题=新的报头({'的Content-Type:应用/ JSON'});
让选项=新RequestOptions({标题:标题});返回this.http.post(URL,身体,期权)
                .MAP(RES =方式> res.json()数据)
                .catch(this.handleError)

请注意,我相信这只是需要POST查询。

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


      }
    }

解决方案

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.

这篇关于如何设置Content-Type和在angular2得到错误415不支持的媒体类型接受的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆