Angular 2,Http和Not设置Content-Type"application/json"

Wan*_*per 3 http-headers angular

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

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);

   }
}
Run Code Online (Sandbox Code Playgroud)

来自Web Api的请求

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
Run Code Online (Sandbox Code Playgroud)

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

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

Thi*_*ier 7

类的post方法Http接受类型的对象RequestOptionsArgs而不是RequestOptions.

class RequestOptionsArgs {
  url : string
  method : string | RequestMethod
  search : string | URLSearchParams
  headers : Headers
  body : any
  withCredentials : boolean
}
Run Code Online (Sandbox Code Playgroud)

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

return this._http.post(url, data, { headers: headers });
Run Code Online (Sandbox Code Playgroud)