Angular2 Headers 未在 POST 上设置

Angular2 Headers not set on POST

我知道有很多这样的问题,但 none 确实解决了我的问题...

我是 Angular2 的新手,正在尝试发出 POST 请求,但我指定的 header 未设置...

我的代码是:

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class LoginService {
  constructor(private http: Http) {
  }

  login(email, pass) {

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

      const user = {"email": email, "password": pass};
      console.log(JSON.stringify(headers));
      return this.http.post("http://localhost/api/users/login", JSON.stringify(user), {headers: headers}).map(res => res.json());
  }
}

当我查看 Chrome 的检查器时,请求 header 看起来像这样:

OPTIONS /api/users/login HTTP/1.1
Host: localhost
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8

不知道为什么它现在在 Access-Control-Request-Headers...

顺便说一句:如果我在 post 人中尝试相同的方法,它工作正常...

感谢您的帮助

编辑: 忘了说,如果我将 "application/x-www-form-urlencoded" 设置为 contet-type,它会在请求中显示 header

你把这个复杂化了,你不需要添加 Content-Type 到这个请求,你也不需要 JSON.stringify 模型,下面的代码应该可以工作。

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class LoginService {
  constructor(private http: Http) { }

  public login(email: string, pass:string): Observable<any>{
    let url: string = 'http://localhost/api/users/login';
    let body: any = {
      email: email,
      password: pass
    };

    return this.http.post(url, body).map((res:Response) => res.json());
  }
}