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

时间:2016-06-02 15:22:32

标签: angular http-headers

我正在尝试在服务中使用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);

   }
}

来自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

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

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

3 个答案:

答案 0 :(得分:7)

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

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

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

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

答案 1 :(得分:1)

在Angular 4及更高版本中设置标题应该现在设置如下:

let headers = new HttpHeaders({         "内容类型":" application / json",         "接受":" application / json"     });

this.http.post(" apiUrl",data,{headers:this.headers})

答案 2 :(得分:0)

RequestOptionsArgs是Angular2中的一个界面,因此您可以将RequestOptions指定为值。