1

I am testing my api as below:

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    </head>
    <body>


        <div onclick="sendData()">Send</div>

        <script>
            function sendData(){

                var sendInfo = {
                    "name" : "test"
                };

                $.ajax({
                    //headers: { 'Access-Control-Allow-Origin': '*' },
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
                        xhr.setRequestHeader("Content-Type","application/json");
                        xhr.setRequestHeader("Accept","application/json");
                },
                url: "http://localhost:8080/someapi",
                data:  sendInfo,
                type: "POST",
                dataType: "json",
                success: function(data){
                    //do something after something is recieved from php
                },
                error: function(){
                    //bad request
                }
            });
        }

        </script>
    </body>
</html>

I am getting below error:

Failed to load http://localhost:8080/someapi: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.

How to solve this?

Michael
  • 2,758
  • 6
  • 28
  • 55
usr_11
  • 438
  • 4
  • 18
  • 1
    I think `Access-Control-Allow-Origin", "*"` should bet set at the end point. i.e `http://localhost:8080/someapi` – Himanshu Upadhyay May 03 '18 at 12:32
  • @HimanshuUpadhyay Adding that header is a security risk more than a fix, but it will work for development purposes (It has to be set on the server). Assuming OP is using localhost as his domain for the website which is doing the XHR requests, you might be looking into a chrome bug (also assuming chrome): https://stackoverflow.com/questions/10883211/deadly-cors-when-http-localhost-is-the-origin – Fabricio20 May 03 '18 at 12:36
  • 2
    `Adding that header is a security risk more than a fix` If you use a wildcard, possibly. However if set to an actual domain it's perfectly fine to use in a production environment – Rory McCrossan May 03 '18 at 12:38
  • yes, @RoryMcCrossan, you are always right. – Himanshu Upadhyay May 03 '18 at 12:43

0 Answers0