【发布时间】:2021-05-23 07:05:52
【问题描述】:
我正在尝试在我的 Angular 应用程序中登录或注册,但是每当我访问 php 文件时,该文件会针对用户 (authentication.php) 对数据库进行 HTTP 调用,我会收到三个错误:
-
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 -
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}} -
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: true 和responseType: "blob" 添加到参数中,因为我在 TS 中没有收到 json,但仍然没有。
【问题讨论】:
-
参考以下链接stackoverflow.com/questions/66173974/…对你也有帮助。