0

I am learning ionic and i have created a simple signup app in ionic 5.

I am getting this error when i try to call api for posting data.

Access to XMLHttpRequest at 'http://localhost:8888/php_project/mango/signup.php' from origin 'http://localhost:8100' 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.

I tried by setting headers in my post request but still getting same error. Here are the headers i am setting for post request:

'Access-Control-Allow-Headers': 'Content-Type',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PUT, POST, GET, OPTIONS, DELETE',

What else need to be done to call api from ionic.

Vinit Singh
  • 1,113
  • 2
  • 21
  • 45

2 Answers2

2

This is an issue caused by misconfigured same-origin policy. This policy prevents JavaScript from making requests across domain boundaries, and has spawned various hacks for making cross-domain requests.

To fix this, CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests. The spec defines a set of headers that allow the browser and server to communicate about which requests are (and are not) allowed.

Seems like you have PHP as your backend API. You will need to enable CORS on your backend to be able to connect from UI.

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

This is a good start for local development. For more information: https://enable-cors.org/server_php.html

cerkiner
  • 1,626
  • 8
  • 16
1

This is because your API has enabled CORS and you are trying to call api from non trusted origin(your localhost). You need to allow CORS for http://localhost:8100 in your api environment setting.

Kishor Kunal
  • 247
  • 1
  • 4