Angular 2,Http和Not设置Content-Type" application / json" [英] Angular 2, Http and Not setting Content-Type "application/json"

查看:119
本文介绍了Angular 2,Http和Not设置Content-Type" application / json"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在服务中使用Angular 2(2.0.0-rc.1)执行简单的Check Login方法。当我尝试将内容类型设置为application / json时,它在发送到我的web api后端时从不设置标题。

I am trying to do a simple Check Login method using Angular 2(2.0.0-rc.1) in a service. When I attempt to set the content-type to application/json it never sets the headers when sending to my web api backend.

import { Injectable } from '@angular/core';
import { HTTP_PROVIDERS, Http, Response, Headers, RequestOptionsArgs, RequestMethod, Request, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Other Modules Left out for Security } from 'Hidden';

@Injectable()
export class LoginService {

private _http: Http;


constructor(http: Http) {
    this._http = http;


}

CheckLogin(model: CredentialModel) {

    let url = 'http://localhost:51671/api/Login';

    let data = JSON.stringify(model);        

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');


    let requestOptions = new RequestOptions({
        method: RequestMethod.Post,
        url: url,
        headers: headers,
        body: data
    });


    console.log(requestOptions);
    console.log(data);

return this._http.post(url, data, requestOptions);

   }
}

OPTIONS /api/Login HTTP/1.1
Host: localhost:51671
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:5616
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2754.0 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
DNT: 1
Referer: http://localhost:5616/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

使用使用PostMan完全相同的数据工作正常!看起来Angular 2使用POST方法发送application / json存在问题。

Using the exact same data using PostMan works fine! Looks like there is an issue with Angular 2 sending application/json using the POST method.

解决此问题的任何帮助都会有所帮助。打开尝试任何建议。

Any help resolving this issue would be helpful. Open to trying any suggestions.

推荐答案

帖子的方法 Http 类接受类型为 RequestOptionsArgs 的对象,而不是 RequestOptions

The post method of the Http class accepts an object of type RequestOptionsArgs and not RequestOptions.

class RequestOptionsArgs {
  url : string
  method : string | RequestMethod
  search : string | URLSearchParams
  headers : Headers
  body : any
  withCredentials : boolean
}

您可以在第三个参数中以字面方式指定它:

You can specify it literally this way within the third parameter:

return this._http.post(url, data, { headers: headers });

这篇关于Angular 2,Http和Not设置Content-Type" application / json"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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