Angular2标头未在POST上设置

时间:2017-05-04 22:18:16

标签: angular http angular2-services

我知道有很多这样的问题,但没有一个能解决我的问题......

我是Angular2中的新手并尝试发出POST请求,但我指定的标题并未设置...

我的代码是:

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的检查员时,请求标题如下所示:

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 中......

顺便说一句:如果我在帖子中尝试同样的话,那就行了......

感谢您的帮助

编辑: 忘了提一下,如果我设置" application / x-www-form-urlencoded"作为contet-type,它确实显示在请求标题

1 个答案:

答案 0 :(得分:1)

您可能会对此进行复杂化处理,您无需向此请求添加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());
  }
}