Sam
Sam

Reputation: 151

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in flight response

I am developing an Angular 4 application with Laravel (Restful API). I have tested the API with Postman. It's working fine but when I call the API from Angular 4 I am getting this error:

enter image description here

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { User } from '../models/user';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AuthService {
 private BASE_URL: string = 'http://localhost/fmfb_hr/public/api';
  private headers: Headers = new Headers({'Content-Type': 'application/json'});
 constructor(private http: Http) {}
login(user): Promise<any> {
let url: string = `${this.BASE_URL}/login`;
return this.http.post(url, user, {headers: this.headers}).toPromise();
}


}

Upvotes: 2

Views: 15234

Answers (2)

Sheraz
Sheraz

Reputation: 276

Try this code add both header in one request, I hope this works

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { User } from '../models/user';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AuthService {
    private BASE_URL: string = 'http://localhost/fmfb_hr/public/api';
    private headers: Headers = new Headers({});
    constructor(private http: Http) {}
    login(user): Promise<any> {
        let url: string = `${this.BASE_URL}/login`;
        this.headers.append('Content-Type','application/x-www-form-urlencoded');
        this.headers.append('Content-Type','application/json');
        return this.http.post(url, user, {headers: this.headers}).toPromise();
    }
}

Upvotes: 2

Meysam Mahmoodi
Meysam Mahmoodi

Reputation: 533

Add these three lines to CORSify your server. If you used Apache as web server, add these lines to your .htaccess file:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET,PUT,POST,DELETE"
Header set Access-Control-Allow-Headers "Content-Type, Authorization"

Upvotes: 12

Related Questions