Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google API + PHP + Ajax Call - Access-Control-Allow-Origin' header is present on the requested resource

I'm using the google API to access my calendar entries via OAuth. Unfortunately I'm getting the following error (server is a local raspi):

Failed to load 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_prompt=auto: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://openhabianpi..' is therefore not allowed access. The response had HTTP status code 405.

My scripts:

Ajax Request

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));
}

I've tried the following, unfortunately without success:

  1. dataType: 'jsonp',

  2. header("Access-Control-Allow-Origin: *");

  3. Setting in .htaccess or apache.conf

Access-Control-Allow-Origin "*"

Thanks in advance for your help!

like image 921
cr1zz Avatar asked Jun 07 '18 18:06

cr1zz


People also ask

How do you fix access-control-allow-Origin header is present on the requested resource?

So to fix, type the target and the origin equally: make you Ajax code request pages/services to http://www.wordicious.com not http://wordicious.com . (Maybe place the target URL relatively, like '/login. php' , without the domain).

How do I fix CORS header access-control-allow-Origin missing?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.


1 Answers

    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);
    }
like image 175
Viral Jadav Avatar answered Oct 09 '22 19:10

Viral Jadav