簡體   English   中英

“嘗試與Chrome擴展程序中的Google Contacts API進行交互時,不會出現”Access-Control-Allow-Origin“標題

[英]“No 'Access-Control-Allow-Origin' header is present” when trying to interact with Google Contacts API from Chrome extension

我的目標是獲得一個Chrome擴展程序,以便能夠將聯系人添加到Google聯系人中。 文件是:

的manifest.json

{
    "manifest_version": 2,
    "name": "My friend joe",
    "version": "1.0",

    "description": "Add Joe to google contacts",

    "browser_action": {},

    "background": {
        "scripts": ["background.js"]
    },

    "permissions": [
        "identity"
    ],

    "oauth2": {
        "client_id": "1038191206887-v1987tg5v07mp166l0pm68qqblojvpll.apps.googleusercontent.com",
        "scopes": ["https://www.google.com/m8/feeds/"]
    }
}

background.js

chrome.browserAction.onClicked.addListener(add_joe);

function add_joe() {
    chrome.identity.getAuthToken({"interactive": true}, add_contact);
    return true;
}

function add_contact(t) {
    console.log('Token: ' + t);
    // Generate the body of the XMLHttpRequest
    xhr_body =
        `<atom:entry xmlns:atom="http://www.w3.org/2005/Atom"
            xmlns:gd="http://schemas.google.com/g/2005">
            <atom:category scheme="http://schemas.google.com/g/2005#kind"
                term="http://schemas.google.com/contact/2008#contact"/>
            <gd:name>
                <gd:fullName>Joe Schmoe</gd:fullName>
            </gd:name>
        </atom:entry>`;

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://www.google.com/m8/feeds/contacts/default/full");
    xhr.setRequestHeader("Content-Type", "application/atom+xml");
    xhr.setRequestHeader("GData-Version", "3.0");
    xhr.setRequestHeader("Authorization", "Bearer " + t);
    xhr.send(xhr_body);
}

出現的錯誤 錯誤


發生錯誤之前采取的步驟:

用google創建了用於Chrome擴展程序的API密鑰 谷歌api

將API密鑰添加到清單。 然后我使用開發者模式將解壓縮的擴展加載到chrome中 鍍鉻擴展

然后我點擊了擴展程序的圖標 在此輸入圖像描述

那是在發生錯誤時,如上面的屏幕截圖所示。 通過單擊“ Inspect views: background page擴展頁面上的Inspect views: background page ”頁面並查看控制台,可以看到這一點。


參考資源:

我正在使用Google Contacts API的“ Creating contacts部分來確定請求標頭和請求正文。 它還說“要創建新聯系人,請發送授權的POST請求”。

如何發送授權請求在他們的JavaScript API客戶端庫文檔中進行了演示。

我知道問題源於發出CORS請求的問題(跨源資源共享)。 該信息也在javascript API客戶端庫文檔中,但是唯一的示例代碼是使用其客戶端庫函數調用。

在輸入我的問題的過程中,我遇到了答案。 我找到的特定文檔是: https : //developer.chrome.com/extensions/xhr 只需添加任何域,我將向CORS請求發出,需要事先在manifest.json列出。 因此,在修改清單后包括:

"permissions": [
        "identity",
        "https://www.google.com/"
    ],

我不再收到錯誤,實際上收到了201 Created狀態代碼響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM