AngularJS2向http post添加标题并不起作用

时间:2016-12-08 11:50:16

标签: http angular cors

我正在尝试将标头添加到我的http帖子请求中,如下所示

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';

@Injectable() 
export class UserService extends ServiceBase {

    apiUrl: string; 
    private contentHeaders = new Headers();

    constructor(private http: Http) {
        super();
        this.apiUrl = appConfig.apiBaseUrl + '/users';
    }

    login(user: User) {
        this.contentHeaders.append('Accept', 'application/json');
        this.contentHeaders.append('Content-Type', 'application/json');
        return this.http.post(
            this.apiUrl+'/sign_in', 
        JSON.stringify({user: user}),
            {headers: this.contentHeaders}
        );
    }
 }

Chrome DevTools中显示的标题:

OPTIONS /api/v1/users/sign_in HTTP/1.1 Host: offers2win.com Connection: keep-alive Pragma: no-cache Cache-Control: no-cache Access-Control-Request-Method: POST Origin: http://evil.com/ User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36 Access-Control-Request-Headers: access-control-allow-credentials, content-type Accept: */* Referer: http://localhost:3000/? Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8

但Chrome浏览器工具网络面板中未显示这些标题。我在这里错过了什么。

1 个答案:

答案 0 :(得分:0)

试试这个

  constructor(private http: Http) { }

  login(username: any, password: any) {
    let body = JSON.stringify({ "email" : username, "password" : password });
    let headers = new Headers({"Content-Type": "application/json"});
    let options = new RequestOptions({headers: headers});
    return this.http.post(APIUrl+"/login", body, options).map(res => res.json());
  }