我尝试在wordpress主题中访问google驱动器,并在下载所选文件时出现以下错误。
XMLHttpRequest无法加载https://drive.google.com/a/mobfish.net/file/d/0B5IETzPj-JCw832h9rdwk/view?usp=drive_web。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://wptest.dev”访问。
(我稍微修改了一下URL,这不是真正的文件ID)
以下是JavaScript代码:
var developerKey = document.getElementById('key').innerHTML;
var clientId = document.getElementById('clientID').innerHTML;
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/drive.readonly'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
gapi.load("client");
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var view = new google.picker.DocsView(google.picker.ViewId.DOCS_IMAGES_AND_VIDEOS)
.setIncludeFolders(true)
.setSelectFolderEnabled(true);
var picker = new google.picker.PickerBuilder().
hideTitleBar().
disableFeature(google.picker.Feature.NAV_HIDDEN).
addView(view).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data.action == google.picker.Action.PICKED) {
var file = data.docs[0];
download(file);
}
}
function download(file) {
console.log("downloading " + file.id);
console.log(file);
var downloadUrl;
if (file.url) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.url);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() {
callback(null);
};
xhr.send();
} else {
callback(null);
}
}
function callback(param) {
console.log(param);
}
也许我忘了在https://console.developers.google.com添加一些设置? 在此先感谢,问候。
答案 0 :(得分:1)
您遇到的问题可能是Cross Origin Security。基本上,大多数Web浏览器都不允许您从自己以外的服务器中提取内容,除非服务器说它没问题。为此,服务器需要在标题中看到可接受的Access-Control-Allow-Origin
。
在此link上找到有关如何在WordPress中启用CORS的教程。您只需要将相应的标头添加到头文件中:
<?php /** @package WordPress @subpackage Default_Theme **/
header("Access-Control-Allow-Origin: *");
?>
<!DOCTYPE html>
您还可以查看这些相关主题:
希望这有帮助!