2017-05-04 81 views
0

我知道有很多這樣的問題,但沒有解決根本問題,我...Angular2頭未設置POST

我在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 

不知道爲什麼它在訪問控制請求報頭現在......

順便說一句:如果我嘗試同樣從郵遞員,它工作正常...

謝謝您幫助

編輯: 忘了提,如果我設置「應用程序/ x-WWW的形式,進行了urlencoded」作爲contet型,它在請求頭顯示

+0

你應該爲你的目的定製一個'httpUtil'服務 – Aravind

回答

1

你一路過來複雜化這一點,你不需要將Content-Type添加到此請求中,您不需要d到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()); 
    } 
}