【发布时间】:2021-01-06 21:11:27
【问题描述】:
当我尝试用 php 连接 angular 时遇到了这个问题
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.
尽管我在我的 php 脚本 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);
这是服务 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);
}
}
【问题讨论】: