Here is my angular --version log
Angular CLI: 11.1.2
Node: 10.19.0
OS: linux x64
Angular: 11.1.1
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router
Ivy Workspace: Yes
Package Version
---------------------------------------------------------
@angular-devkit/architect 0.1101.2
@angular-devkit/build-angular 0.1101.2
@angular-devkit/core 11.1.2
@angular-devkit/schematics 11.1.2
@angular/cli 11.1.2
@schematics/angular 11.1.2
@schematics/update 0.1101.2
rxjs 6.6.3
typescript 4.1.3
I am using PHP (Codeigniter) as my server-side language running on apache2.
I want to call an API from angular with auth headers and X API key.
Here is my angular code.
import { HttpClient, HttpHeaders } from '@angular/common/http';
// import {Http, Headers} from '@angular/http';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private http:HttpClient){
}
title = 'My First Application';
apiCheck(){
const httpOptions = {
headers: new HttpHeaders()
.set('Authorization','Basic YWRtaW46MTIzNA==')
.set("x-api-key","sdfasdfasdfsadfsadfsdaf")
.set("token","sadfsadfasdf")
.set("Content-Type","application/json")
}
let request = this.http.get('http://localhost/ci/index.php/api/V1/againTest', httpOptions);
request.subscribe(
data=>{
console.log(data);
}
);
}
}
This is working fine when I request this API from Postman. But got this error when I called this API from the angular end.
I have enabled the cors from the server end by adding this.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
I have tried with the documentation for proxy setting also https://angular.io/guide/build#proxying-to-a-backend-server
here is my proxy.conf.json
{
"/api/*": {
"target": "http://localhost",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
add register it on angular.json file.
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "my-dream-app:build",
"proxyConfig": "./proxy.conf.json"
},
I have not found any working answer from anywhere.
Thanks in advance for your help.
question from:
https://stackoverflow.com/questions/66059420/cors-policy-error-with-angular-11-and-php-api