"No 'Access-Control-Allow-Origin' header is present" 尝试与 Chrome 分机中的 Google 联系人 API 互动时

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

出现的错误


发生错误之前采取的步骤:

为 chrome 扩展创建了 API 密钥 google

向清单添加了 API 键。然后我使用开发者模式

将解压后的扩展加载到chrome

然后我点击了扩展程序的图标

这就是上面截图所示的错误发生的时候。这可以通过单击扩展页面上的 Inspect views: background page 并查看控制台来查看。


引用的资源:

我正在使用 Google Contacts APICreating contacts 部分来确定请求 headers 和请求 body。它还说 "To create a new contact, send an authorized POST request".

他们的 javascript API client library 文档中演示了如何发送授权请求。

我知道问题源于发出 CORS 请求(Cross-Origin-Resource 共享)的问题。该信息也在 javascript API client library docs 中,但唯一的示例代码是使用他们的客户端库函数调用。

在输入问题的过程中,我找到了答案。我找到的具体文档是:https://developer.chrome.com/extensions/xhr。只需要添加我将要发出 CORS 请求的任何域,这些域需要预先在 manifest.json 中列出。所以在修改我的清单以包括:

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

我不再收到错误,实际上收到了 201 Created 状态代码响应。