代码之家  ›  专栏  ›  技术社区  ›  cr1zz

请求的资源上有google api+php+ajax call-access control allow origin'头

  •  6
  • cr1zz  · 技术社区  · 7 年前

    我正在使用google api通过oauth访问我的日历条目。 很遗憾,我收到以下错误(服务器是本地RASPI):

    加载失败 https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=online&client_id= ***-***.apps.googleusercontent.com&redirect_uri=http%3a%2f%2fopenhabianpi。 %2FsmartHome%2Fphp%2Fscripts%2Fscript.oauth2callback.php&state&scope=https%3A%2F%2Fwww.googleapis.com%2fauth%2Fcalendar.readonly&approval\u prompt=auto:对飞行前请求的响应未通过访问控制检查:请求的res上不存在“访问控制允许源”头乌尔斯起源 http://openhabianpi . 因此不允许访问。响应的http状态代码为405。

    我的脚本:

    Ajax请求

    var termine = function (){
         $.ajax({
            type: "POST",
            url: "php/ajax/ajax.termine.php",
            data: {
                action: 'get_termine'
            },n
            success: function(response) {
                console.log(response);
            }
        });
    }
    

    ajax.termine.php网站

    require dirname(dirname(__FILE__)).'/vendor/autoload.php';
    
    $client = new Google_Client();
    $client->setAuthConfig(dirname(dirname(__FILE__)).'/config/client_secret.json');
    $client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
      $client->setAccessToken($_SESSION['access_token']);
      $calendarId = 'primary';
      $optParams = array(
        'maxResults' => 10,
        'orderBy' => 'startTime',
        'singleEvents' => TRUE,
        'timeMin' => date('c'),
      );
    
      $service = new Google_Service_Calendar($client);
      $results = $service->events->listEvents($calendarId, $optParams);
      if (count($results->getItems()) == 0) {
        print "No upcoming events found.\n";
      } else {
        print "Upcoming events:\n";
        foreach ($results->getItems() as $event) {
          $start = $event->start->dateTime;
          if (empty($start)) {
            $start = $event->start->date;
          }
          printf("%s (%s)\n", $event->getSummary(), $start);
            echo date('c');
        }
      }
    } else {
      $redirect_uri = 'http://openhabianpi.***.***/smarthome/php/scripts/script.oauth2callback.php';
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
    

    script.oauth2callback脚本

    <?php
    require_once dirname(dirname(__FILE__)).'/vendor/autoload.php';
    session_start();
    
    $client = new Google_Client();
    $client->setAuthConfigFile(dirname(dirname(__FILE__)).'/config/client_secret.json');
    $client->setRedirectUri('http://openhabianpi.***.***/smarthome/php/scripts/script.oauth2callback.php');
    $client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
    if (! isset($_GET['code'])) {
      $auth_url = $client->createAuthUrl();
      header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    } else {
      $client->authenticate($_GET['code']);
      $_SESSION['access_token'] = $client->getAccessToken();
      $redirect_uri = 'http://openhabianpi.***.***/smarthome/';
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
    

    很不幸,我尝试过以下方法,但没有成功:

    1. 数据类型:“jsonp”,

    2. header(“访问控制允许来源:”);

    3. 在.htaccess或apache.conf中设置

    访问控制允许源“*”

    提前谢谢你的帮助!

    4 回复  |  直到 7 年前
        1
  •  4
  •   Viral Jadav    7 年前
        if (isset($_SERVER['HTTP_ORIGIN'])){
            header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');    // cache for 1 day
        }
        // Access-Control headers are received during OPTIONS requests
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') 
        {
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
                header("Access-Control-Allow-Methods: GET, POST,OPTIONS");         
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
            exit(0);
        }
    
        2
  •  0
  •   Korri    7 年前

    不能使用ajax作为 $client->createAuthUrl() 将显示登录页。

    通过以下步骤,您仍然可以停留在同一页上:

    • 正常开放 ajax.termine.php 在新的标签上。

    window.open('php/ajax/ajax.termine.php', '_blank');

    • 将重定向uri设置为只包含javascript的空白页。
    • 使用此javascript更改父页面url。

    window.top.location.href = 'http://openhabianpi.***.***/smarthome/';

        3
  •  0
  •   Pradeep Kumar Kushwaha    7 年前

    您只需访问您的google开发者帐户,然后在api凭证下添加您的web服务器地址或ip地址。

    参观 console.developers.google.com

    然后选择您的项目。 然后选择凭据。然后选择您的api密钥。然后选择应用程序限制,然后选择http referers address并添加您的地址。

    enter image description here

    希望它能解决你的问题。

        4
  •  0
  •   cr1zz    7 年前

    以下脚本通过ajax工作(必须为此使用服务帐户):

        <?php
        /**
        * Session aufbauen und user check
        */
        session_start();
    
        require dirname(dirname(__FILE__)).'/vendor/autoload.php'; //Google API via Composer
    
        $json_path = '***PATH to service account credential JSON***';
    
        $client = new Google_Client();
    
        $client->setAuthConfig($json_path);
        $client->useApplicationDefaultCredentials();
        $client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
    
        $client->setApplicationName("***Your Appname***");
    
        $service = new Google_Service_Calendar($client);
    
        $calendarId = '***Your CAL ID***';
        $optParams = array(
           'maxResults' => 10,
            'orderBy' => 'startTime',
            'singleEvents' => TRUE,
            'timeMin' => date('c'),
        );
    
      $results = $service->events->listEvents($calendarId, $optParams);
      if (count($results->getItems()) == 0) {
        print "";
      } else {
        foreach ($results->getItems() as $event) {
          $start = $event->start->dateTime;
          if (empty($start)) {
            $start = $event->start->date;
          }
    
          $date = date("d.m.Y", strtotime($start));
          $time = date("G:i", strtotime($start));
    
          $today = date("d.m.Y");
    
          if ($date == $today){
            $array[] = array(
              "datum" => $date,
              "time" => $time,
              "termin" => $event->summary
            );
          }
        }
      }
    
      echo json_encode($array);