0

I'm trying to use a website of mine as the mysql backend for my angularjs app but when i try to post data to the server i run into this error

XMLHttpRequest cannot load www.domain.com/backend_script.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '127.0.0.1:60728' is therefore not allowed access. The response had HTTP status code 500.

(I removed the https:// and stuff because im too low in rep to post links)

I added this in the top of my php file on the domain just to test but its still not working with the header set, this is what my script looks like.

<?php
    require_once 'adb-functions.php';

    header('Access-Control-Allow-Origin: http://127.0.0.1:60728/');

    $data = json_decode(file_get_contents("php://input"));
    $q = trim($data->query);
    $all = $data->all;
    //print_r(2);
    function render($query)
    {
        global $q;

        $renderedQb = '';
        preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $q, $commands);
        //print_r($commands[0]);
        $commands = $commands[0];
        if($commands[0] ==="get"){
            if(trim($commands[1]) === "all") { 
                $renderedQ = "SELECT * FROM `".$commands[2]."`;"; 
                return $renderedQ;
            }
            elseif (!empty($commands[4])) {
                if($commands[4]==='spec')
                {
                    $renderedQ = "SELECT * FROM `".$commands[1]."` WHERE `".$commands[2]."`='".$commands[3]."';";
                    return $renderedQ;
                }
                else
                {
                    echo 'ERROR: Mismatch query template';
                }
            }
            else 
            {
               $renderedQ = 'SELECT * FROM `'.$commands[1].'` WHERE id='.$commands[2].';';
               return $renderedQ;
            }
        }
        else
        {
            return $query;
        }
    }

    try 
    {
        $query = $handler->query(render($q));
        if($query){

                if($all==true){
                    print_r(json_encode($query->fetchAll(PDO::FETCH_ASSOC)));
                }
                else
                {
                    print_r(json_encode($query->fetch(PDO::FETCH_ASSOC)));
                }

        }else{
            //echo 'Error';
        }
    } 
    catch (PDOException $e) 
    {
        echo $e;   
    }
?>

the rest of the script is just the execution of the query which is sent from a factory function i made in angularjs here.

fact.get = function(query, all){ return $http.post('https://example.com/script.php', {'query': query, 'all': all}); };

is there a way to set the headers in angularjs? or even a totally different way to accomplish this in general?

Maciej Pulikowski
  • 2,457
  • 3
  • 15
  • 34

0 Answers0