John Davidson

php - "CORS: No 'Access-Control-Allow-Origin' header is present ", but it is present

0 comments
Message:


I'm trying to log in or register in my Angular app, but whenever I access to the php file which does the HTTP calls to the DB regarding users (authentication.php), I get three errors:



  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




(The last one says GET for login, POST for register)


In authentication.php I have the following code regarding headers:


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

In openDB.php:


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

In 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');

I've tried writing those headers in authentication.php, adding OPTIONS to Allow-Methods and allow all origins with *, but I still get the same three errors.


My user.service.ts has the following code regarding these operations:


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();
}

(I'm just pasting register because login is a bit weirdly done and the problem here seems to be with authentication.php, no matter what operation it makes)


I've also tried adding withCredentials: true and responseType: "blob" to params since I'm not receiving a json in the TS, but still nothing.



My Answer:
PHP is a server-side scripting language that is commonly used for web development. It can be embedded into HTML code and is often used to create dynamic web pages. PHP stands for Hypertext Preprocessor and is open source, meaning it is free to use and modify. It is a popular choice for building websites and web applications due to its flexibility and ease of use.

Rate this post

3 of 5 based on 1646 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us