Daffa Reri
Daffa Reri

Reputation: 5

javascript - No 'Access-Control-Allow-Origin' header is present on the requested resource. i dont know what to do

well, this message always showed on my console.. can someone help me to fix this out?.. btw this is ionic.. this is my controller.js

angular.module('directory.controllers', [])

.controller('EmployeeIndexCtrl', function ($scope, EmployeeService, $http) {

    $scope.searchKey = "";

    $scope.clearSearch = function () {
        $scope.searchKey = "";
        findAllEmployees();
    }

    $scope.search = function () {
        EmployeeService.findByName($scope.searchKey).then(function (employees) {
            $scope.employees = employees;
        });
    }
    var findAllEmployees = function() {
        $http({
          method: 'GET',
          url: 'https://miudr.000webhostapp.com'
        }).then(function (res){
          $scope.employees = res.data;
          console.log(res);
        })
    }
    findAllEmployees();

})

.controller('EmployeeDetailCtrl', function ($scope, $stateParams, EmployeeService) {
    EmployeeService.findById($stateParams.employeeId).then(function(employee) {
        $scope.employee = employee;
    });
})

.controller('EmployeeReportsCtrl', function ($scope, $stateParams, EmployeeService) {
    EmployeeService.findByManager($stateParams.employeeId).then(function(employees) {
        $scope.employees = employees;
    });
});

and this is my json.php

<?php
header("Content-type:application/json");

 $connection = mysqli_connect("localhost", "root", "", "miudr") or die("Error " . mysqli_error($connection));

 $sql = "select * from data";
 $result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));

 while ($row = mysqli_fetch_assoc($result)) {
     $data[] = $row;
 }

 echo json_encode($data, JSON_PRETTY_PRINT);

 mysqli_close($connection);
 ?>

php file is located on my hosting.. but anyway i hide my username and password as root and "".. i dont know everytime i try to show this json.. its not showing me the result.. but showing me No'Access blablabla'

btw sorry for my bad english

Upvotes: 0

Views: 84

Answers (1)

Desmond
Desmond

Reputation: 149

You have to allow your backend to accept the request. Something like this

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

This will accept from all due to "*". If you only wish to accept requests from your IP, replace * with your IP.

Else you can consider using JSONP. Just add dataType: 'JSONP' to your $http object.

Upvotes: 3

Related Questions