guy
guy

Reputation: 213

CORS error when using PHP on IIS on server side and angular 4 on client side

I have 2 web sites that communicate with REST API on my server side. The main web site has the main domain and the second website has a sub domain. for example www.example.com and www.admin.example.com

i have a REST API on the www.example.com root directory and when the www.example.com address to the API everything is OK, but when www.admin.example.com is trying to address to the API, i get an error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://admin.example.com' is therefore not allowed access.

I have this PHP code line on my RestController.php file:

header("Access-Control-Allow-Origin: *");

I also tried to add to my web.config the following code:

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="*" />
      <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
      <add name="Access-Control-Max-Age" value="1000" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

but still i get the the No 'Access-Control-Allow-Origin' header error, or the error "The 'Access-Control-Allow-Origin' header contains multiple values '*, *, but only one is allowed."

i don't know if it's important, but we are using Angular 4 for client side.

Does anyone has an idea what is the problem, is it an IIS issue or PHP issue or even client side issue?

Thank You

Upvotes: 1

Views: 1982

Answers (2)

Lex Li
Lex Li

Reputation: 63163

Previously you have to either write your own code or other hacking methods, but now Microsoft ships an official IIS extension, called IIS CORS Module.

You can configure CORS responses easily after installing it.

Upvotes: 2

Ludwig
Ludwig

Reputation: 1272

First you should set the Access-Control-Allow-Origin just in one place. I would recommend to do that in your php controller. Otherwise you might run into that "The 'Access-Control-Allow-Origin' header contains multiple values '*, *, but only one is allowed."

Second if you are doing a GET request everything is OK but if you are doing a POST request you might run into the "Response to preflight request doesn't pass access control check..". The reason for that is that your browser sends an OPTIONS preflight request. This request you have to handle on the server side (like you do the post) to be allowed and processed.

You can read more here about preflight requests: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

Further you can find some more information in this thread: CORS with php headers

Upvotes: 0

Related Questions