繁体   English   中英

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

[英]Angular 2, Http and Not setting Content-Type “application/json”

我试图在服务中使用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存在问题。

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

Http类的post方法接受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 });

现在应该像这样设置Angular 4和更高版本中的Headers:

let headers = new HttpHeaders({“content-type”:“application / json”,“Accept”:“application / json”});

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM