【问题标题】:"CORS: No 'Access-Control-Allow-Origin' header is present ", but it is present“CORS:不存在‘Access-Control-Allow-Origin’标头”,但存在
【发布时间】:2021-05-23 07:05:52
【问题描述】:

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

  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 并允许所有带有 * 的来源,但我仍然遇到相同的三个错误。

我的user.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,不管它做什么操作)

我也尝试将withCredentials: trueresponseType: "blob" 添加到参数中,因为我在 TS 中没有收到 json,但仍然没有。

【问题讨论】:

标签: php angular header cors


【解决方案1】:

您似乎没有在 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 访问控制错误)

【讨论】:

  • 这不起作用,我猜是因为您忘记更改 HttpHeaders 的 HttpParams。但是,我一直在其他一些文件中使用这样的参数,它们工作得很好,以及 .php 文件中的标题。
猜你喜欢
  • 2014-08-20
  • 2016-10-30
  • 1970-01-01
  • 2016-05-07
  • 2016-10-30
  • 2016-11-06
  • 2017-12-11
  • 2021-10-20
相关资源
最近更新 更多