php - “CORS:不存在‘Access-Control-Allow-Origin’标头”,但存在
问题描述
我正在尝试在我的 Angular 应用程序中登录或注册,但是每当我访问对用户 (authentication.php) 进行 HTTP 调用的 php 文件时,我都会收到三个错误:
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 并允许所有带有 * 的来源,但我仍然遇到相同的三个错误。
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"
解决方案
您似乎没有在 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访问控制错误)
推荐阅读
- amazon-web-services - 发布端口时,Swarm 中的 Docker 服务无法连接到 AWS RDS
- jupyter-notebook - 依次调用多个 Jupyter Notebook
- c++ - 在 VisualStudio 程序中输入 cin 参数
- css - 使用 tailwind @apply 函数的 Angular 组件特定样式
- java - 将数组中的变量添加到另一个数组中
- laravel - Laravel - 如何在 Laravel 应用程序中捕获所有异常并防止用户看到异常
- javascript - 如何将 mongodb 时间戳转换为实际日期?
- .net - 在 Jenkins 的声纳扫描阶段生成的测试结果文件和覆盖率文件存在问题
- excel - 将问题 PDF 复制并粘贴到 Excel
- java - 如何解决 pyspark Databricks 中的 GC 开销