3

How to allow XMLHttpRequest in angular. because I have getData.php

and the error is Access to XMLHttpRequest at 'http://localhost:8888/*****/****/getData.php' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

ABC
  • 752
  • 4
  • 17
  • 40

1 Answers1

-1

Your problem doesn't come from your js, but from your server which doesn't allow CORS request (request from another server). (even thought your request come from localhost to localhost since the ports are different they are considered 2 differents server)

You'll need to allow CORS request using the Access-Control-Allow-Origin header in your http requests

more details on this answer from apsillers(don't forget to upvote him if it solved the problem)

jonatjano
  • 3,576
  • 1
  • 15
  • 20
  • I already import httpclient in my global.service.ts and I use Global Service – ABC Sep 06 '19 at 07:43
  • @ABC since you didn't talk about it I couldn't know, removed the part about it – jonatjano Sep 06 '19 at 07:45
  • In my global.service.ts - ```headers = { 'Accept': 'application/json, text/plain, */*', 'Access-Encoding': 'gzip, deflate', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token'}``` – ABC Sep 06 '19 at 07:50
  • 1
    @ABC you need to add these header server-side – jonatjano Sep 06 '19 at 07:52
  • in the server.ts? – ABC Sep 06 '19 at 08:07
  • @ABC in the php script, using [the header function](https://www.php.net/manual/fr/function.header.php) – jonatjano Sep 06 '19 at 08:26
  • in my ```executeTask.php``` I already put ``` – ABC Sep 06 '19 at 08:30
  • in ```getData.php``` here's the code ``` – ABC Sep 06 '19 at 08:31
  • @ABC I think you should also have all the header calls in `getData.php` or include`executeTask.php` in it, your browser is looking for `getData` so it don't care about the content of `executeTask` unless you explicitely include it somewhere – jonatjano Sep 06 '19 at 08:34
  • @ABC then I don't know I'm sorry – jonatjano Sep 06 '19 at 08:37
  • if i add the header() should it needed to call or doesn't need to call it? – ABC Sep 06 '19 at 08:39
  • ```Access to XMLHttpRequest at 'http://localhost:8888/templogger/services/getData.php' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.``` – ABC Sep 06 '19 at 08:42
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/199061/discussion-between-jonatjano-and-abc). – jonatjano Sep 06 '19 at 08:47