Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

“Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response”

Tags:

angular5

service.ts :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

const httpOptions = {
    // headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:8080', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers':'X-Requested-With' }),
    headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:4200', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Credentials':'true','Access-Control-Allow-Headers':'X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization','Access-Control-Expose-Headers':'xsrf-token' }),
    params: new HttpParams({})
};


@Injectable()
export class DemoService {

    constructor(public http: HttpClient) { }

    postData(doctor) {
        let new_doctor = JSON.stringify(doctor);
        return this.http.post('http://a.com/api/doctors/doctor', new_doctor, httpOptions);
    }

    get_doctor_list() {
        return this.http.get('http://a.com/api/doctors/doctor');
    }

    update_doctor_details(data,id) {
        let details = JSON.stringify(data);
        return this.http.put('http://a.com/api/doctors/doctor/id/' + id, details, httpOptions);
    }
}


component

    onSubmit(createdoctor:NgForm) {
        this.doctor_details = createdoctor.value;
        this.notvalid = createdoctor.valid == true?false:true;
        let date = new Date();
        let created_date = this.datePipe.transform(date, 'yyyy-MM-dd');
        this.doctor_details.Id = this.maxid;
        this.doctor_details.create_date = created_date;
        this.doctor_details.status = "1";
        this._demoService.postData(this.doctor_details).subscribe(
            error => {
                console.error("Error saving data!");
            }
        );
    }

But I got the error :

Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

I am a beginner in angular 5. How can I fix this issue?

like image 344
ashokkiran Avatar asked Nov 03 '25 05:11

ashokkiran


1 Answers

CORS headers, those that start with Access-Control- are response headers, they must be set by and sent from the server to the browser, not the other way around, that's the reason for your error

like image 67
Meme Composer Avatar answered Nov 06 '25 04:11

Meme Composer