2017-05-04 84 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()); 
    } 
}