简体   繁体   中英

Angular2 Headers not set on POST

I know there are a lot of questions like this but none did solved my issue...

I'm new in Angular2 and trying to make a POST request but the headers I specify aren't set...

My code is:

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());
  }
}

When I look in Chrome's inspector the request header looks like this:

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

Dont know why it's in the Access-Control-Request-Headers now...

Btw: if I try the same from in post man, it works fine...

Thanks for your help

EDIT: Forgot to mention that if I set "application/x-www-form-urlencoded" as contet-type, it does show in the request header

You are way over complicating this, you do not need to add Content-Type to this request, you do not need to JSON.stringify the model either, this code below should work.

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());
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM