i am having this issue when i try to connect angular with php
Access to XMLHttpRequest at 'http://localhost/mascotas/getAll.php' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
despite of i have the headders configured in my php script getAll.php
<?php
header("Access-Control-Allow-Origin: http://localhost:4200");
$bd = include_once "bd.php";
$sentencia = $bd->query("select id, nombre, raza, edad from mascotas");
$mascotas = $sentencia->fetchAll(PDO::FETCH_OBJ);
echo json_encode($mascotas);
and this is the service mascotas.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Mascota } from "../classes/mascota";
import { environment } from "../../environments/environment";
@Injectable({
providedIn: 'root'
})
export class MascotasService {
baseUrl = environment.baseUrl
constructor(private http: HttpClient) { }
getMascotas() {
return this.http.get(`${this.baseUrl}/getAll.php`);
}
getMascota(id: string | number) {
return this.http.get(`${this.baseUrl}/get.php?idMascota=${id}`);
}
addMascota(mascota: Mascota) {
return this.http.post(`${this.baseUrl}/post.php`, mascota);
}
deleteMascota(mascota: Mascota) {
return this.http.delete(`${this.baseUrl}/delete.php?idMascota=${mascota.id}`);
}
updateMascota(mascota: Mascota) {
return this.http.put(`${this.baseUrl}/update.php`, mascota);
}
}
By default, you can't bypass this. The server you are making the request to has to implement CORS to grant JavaScript from your website access. Your JavaScript can't grant itself permission to access another website. You have to manually edit server config file, even after you enable it you will open your self to many vulnerability that allows an attacker to inject JavaScript code into a website, so that it originates from the attacked website from the browser point of view. Here a more descriptions https://security.stackexchange.com/questions/8264/why-is-the-same-origin-policy-so-important
One other fixes are to create proxy https://levelup.gitconnected.com/fixing-cors-errors-with-angular-cli-proxy-e5e0ef143f85
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.