Getting Cors error on post call of xml external API when adding header request

  Kiến thức lập trình

I am calling an external API whose request and response both are in xml. When I am adding header request getting cors error on network console. When I am removing all header request then getting 500 error in network console of browser. I am sending all the correct header as per requirement, getting below error. The test url is only for sample.

“Access to XMLHttpRequest at ‘https://some-test-url.test’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

app.component.ts

import { Component, OnInit } from '@angular/core';
import { BackendApiService } from  './service/backend-api.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private restApi: BackendApiService) { 
   
   
  }
  title = 'project';

  ngOnInit(): void {
 this.callPadesApi();
}
callPadesApi(){
  this.restApi.signinxml().subscribe((data: any) => {
  },
    (error) => {
      console.log(error)
    }
  )
}
}

backend-api.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class BackendApiService {

  constructor(public http: HttpClient) { }
signinxml(){
   let headers = new HttpHeaders();
    headers = headers.append('Content-Type', 'text/xml');
    headers = headers.append('access-control-allow-origin','*');
    headers = headers.append('Access-Control-Allow-Credentials','true');
    headers = headers.append('Access-Control-Allow-Method','HEAD,GET,POST');
    headers = headers.append('Access-Control-Allow-Headers','*');
    const xhr = new XMLHttpRequest();
    let request = '<request>' 
    '<username>Username</username>' 
    '<password>Password</password>' 
    '</request>';
   /* xhr.open("POST", "https://some-test-url.test", true);
    xhr.setRequestHeader('Content-Type', 'text/xml');
    xhr.setRequestHeader('access-control-allow-origin','http://localhost:4200/');
    xhr.withCredentials = true;
    xhr.send(request);
    */
   return this.http.post('https://some-test-url.test',request,{headers: headers, responseType: 'text' });
}  
}

LEAVE A COMMENT