首页 > 解决方案 > “CORS:不存在‘Access-Control-Allow-Origin’标头”,但存在

问题描述

我正在尝试在我的 Angular 应用程序中登录或注册,但是每当我访问对用户 (authentication.php) 进行 HTTP 调用的 php 文件时,我都会收到三个错误:

  1. Access to XMLHttpRequest at 'http://localhost/authentication.php?command=login' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

  2. ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"http://localhost/authentication.php","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost/authentication.php: 0 Unknown Error","error":{"isTrusted":true}}

  3. GET http://localhost/authentication.php?command=login net::ERR_FAILED

(最后一个说 GET 用于登录,POST 用于注册)

authentication.php我有以下关于标题的代码:

require "openDB.php";
include "validators/usuarioValidator.php";

openDB.php

header('Access-Control-Allow-Origin: http://localhost:4200');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: PUT, DELETE, POST, GET');

validators/usuarioValidator.php

header('Access-Control-Allow-Origin: http://localhost:4200');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: PUT, DELETE, POST, GET');

我已经尝试在 中编写这些标头authentication.php,将 OPTIONS 添加到 Allow-Methods 并允许所有带有 * 的来源,但我仍然遇到相同的三个错误。

Myuser.service.ts有以下关于这些操作的代码:

register(user : any, key : string) : Promise<any>{
    let parametros = new HttpParams().set("command", "register");

    user.verif = key;

    return this.http.post(this.url, user, {params: parametros}).toPromise();
  }

(我只是粘贴注册,因为登录有点奇怪,这里的问题似乎与authentication.php,无论它进行什么操作)

由于我没有在 TS 中收到 json,因此我也尝试向参数添加withCredentials: true和,但仍然没有。responseType: "blob"

标签: phpangularheadercors

解决方案


您似乎没有在 HTTP 请求正文中正确设置标头,请尝试以下代码,

register(user : any, key : string) : Promise<any>{
    let parametros = new HttpParams().set("command", "register");

    user.verif = key;

    return this.http.post(this.url, user, {Headers: parametros}).toPromise();
  }

此外,如果您使用HTTPClient包发出请求,那么设置自定义标头有点困难。如果您可以通过使用axios或类似的包来防止某些问题(如CORS访问控制错误)


推荐阅读