【问题标题】:XMLHttpRequest blocked by cors in angular-phpXMLHttpRequest 被 angular-php 中的 cors 阻止
【发布时间】: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);
  }
}

【问题讨论】:

    标签: php angular cors


    【解决方案1】:

    默认情况下,您无法绕过这一点。您向其发出请求的服务器必须实施 CORS 以从您的网站访问中授予 JavaScript。您的 JavaScript 无法授予自己访问其他网站的权限。您必须手动编辑服务器配置文件,即使启用它后,您也会发现许多漏洞,这些漏洞允许攻击者将 JavaScript 代码注入网站,因此从浏览器的角度来看,它源自被攻击的网站。 这里有更多描述https://security.stackexchange.com/questions/8264/why-is-the-same-origin-policy-so-important

    另一个修复是创建代理https://levelup.gitconnected.com/fixing-cors-errors-with-angular-cli-proxy-e5e0ef143f85

    【讨论】:

      猜你喜欢
      • 2018-02-26
      • 2019-12-16
      • 2022-01-24
      • 2022-01-01
      • 2020-03-12
      • 2021-09-05
      • 2020-07-25
      • 1970-01-01
      • 2020-11-23
      相关资源
      最近更新 更多