簡體   English   中英

未在POST上設置Angular2標頭

[英]Angular2 Headers not set on 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

現在不知道為什么它在訪問控制請求標頭中 ...

順便說一句:如果我在郵遞員中嘗試同樣的方法,那就很好...

謝謝你的幫助

編輯:忘了提及,如果我將“ application / x-www-form-urlencoded”設置為競爭類型,它的確會顯示在請求標頭中

您無需為此復雜化,無需向此請求添加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());
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM