2016-10-22 100 views
1

我使用PHP發展RESTFul API。例如下面的代碼是針對一個如果這些APIs:請求頭字段訪問控制允許來源是不允許

<?php 

    require('includes/config.php'); 

     $data = array(); 

     try { 
       $stmt = $db->query('SELECT postID, postTitle, postDesc, postDate,tags FROM blog_posts where inMain=inMain ORDER BY postID DESC LIMIT 5'); 
       $error = false; 
       $message = "ok"; 
       $i=0; 
       while($row = $stmt->fetch()){ 

        $tags = explode(",",$row['tags']); 
        $finalTags = array();   
        foreach($tags as $item) { 
         if($item != '' && $item != ' '){ 
          array_push($finalTags,strtolower(trim($item))); 
         } 
        } 

        array_push($data, [ 
         'id' => $row['postID'], 
         'title' => $row['postTitle'], 
         'desc' => $row['postDesc'], 
         'date' => $row['postDate'], 
         'tags' => $finalTags 
        ]); 

       } 
      } catch(PDOException $e) { 
       $message = $e->getMessage(); 
       $error = true; 
      } 
    $response = array(); 
    $response["data"] = $data; 
    $response["error"] = $error; 
    $response["message"] = $message; 

header('Access-Control-Allow-Origin: *'); 
header('Access-Control-Allow-Credentials: true'); 
header('Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT'); 
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'); 
header('Content-Type: application/json'); 

echo json_encode($response); 
?> 

從瀏覽器調用這個API它工作正常。但是當我把它從我的JavaScript得到以下錯誤:

​​

我試圖調用從AngularJs這個API如下:

app.factory("Data", ['$http', 'toaster', 
    function ($http, toaster) { // This service connects to our REST API 

     var serviceBase = 'http://www.example/v1/'; 
     var conf= { headers: { 
      'Access-Control-Allow-Origin':'*', 
      'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS', 
      'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token', 
      'Content-Type': 'application/json' 
     } 
     }; 

     var obj = {}; 
     obj.toast = function (data) { 

      toaster.pop(data.status, "", data.message, 10000, 'trustedHtml'); 
     } 
     obj.get = function (q) { 
      return $http.get(serviceBase + q,conf).then(function (results) { 
       return results.data; 
      }); 
     }; 
     obj.post = function (q, object) { 
       return $http.post(serviceBase + q, object, conf).then(function (results) { 
       return results.data; 
      }); 
     }; 
     return obj; 
}]); 

有什麼問題嗎?因爲您可以在請求和響應中設置所需的標題?它與託管我使用?

回答

0

服務器(PHP)也需要允許CORS。將以下標題添加到PHP腳本的開頭:

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

我已經做了。請參閱上面附上的代碼 –

+0

標題必須在從服務器發送任何輸出之前。所以,它應該在require('includes/config.php')之前。 – Olantobi

相關問題