如何在Google Cloud Endpoints Javascript客户端中设置自定义标头?

时间:2022-08-06 23:11:49

I can fetch a list of blog posts from Google Cloud Endpoints using the Javascript Client:

我可以使用Javascript客户端从Google Cloud Endpoints获取博客帖子列表:

gapi.client.blog.posts.list().execute(function (resp) {
  console.log(resp);
});

But I need to set a custom header value in the Google Cloud Endpoints request that contains a user token (this could be an access token from Facebook). How can I do that using the Javascript Client from Google? I could solve this by not using the Javascript Client from Google, but I would rather use it.

但我需要在包含用户令牌的Google Cloud Endpoints请求中设置自定义标头值(这可能是来自Facebook的访问令牌)。如何使用Google的Javascript客户端执行此操作?我可以通过不使用谷歌的Javascript客户端解决这个问题,但我宁愿使用它。

https://developers.google.com/appengine/docs/java/endpoints/consume_js https://developers.google.com/api-client-library/javascript/reference/referencedocs

https://developers.google.com/appengine/docs/java/endpoints/consume_js https://developers.google.com/api-client-library/javascript/reference/referencedocs

edit

编辑

It seems I can pass the custom header value like this:

我似乎可以像这样传递自定义标头值:

gapi.auth.setToken({
    access_token: 'this is my custom value'
});

Doesn't seem good practice though. Is there a better way to do this?

虽然看起来不是很好的做法。有一个更好的方法吗?

2 个解决方案

#1


1  

You can now do this using gapi.client.request, for example:

您现在可以使用gapi.client.request执行此操作,例如:

gapi.client.init({
    'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
    'scope': 'your_scope'
}).then(function() {
    return gapi.client.request({
        'path': 'http://path/to/your/endpoints/api',
        'headers': { 'mycustomheader': 'myvalue' }
    })
}).then(function(response) {
    console.log(response.result);
}, function(reason) {
    console.log('Error: ' + reason.result.error.message);
});

See also the Getting Started page of the Google API Javascript Client documentation.

另请参阅Google API Javascript客户端文档的“入门”页面。

#2


0  

Try using the header normally, but fetching the token and adding a variable containing it where you need the token to show.

尝试正常使用标题,但是获取标记并在需要标记显示的地方添加包含标记的变量。

#1


1  

You can now do this using gapi.client.request, for example:

您现在可以使用gapi.client.request执行此操作,例如:

gapi.client.init({
    'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
    'scope': 'your_scope'
}).then(function() {
    return gapi.client.request({
        'path': 'http://path/to/your/endpoints/api',
        'headers': { 'mycustomheader': 'myvalue' }
    })
}).then(function(response) {
    console.log(response.result);
}, function(reason) {
    console.log('Error: ' + reason.result.error.message);
});

See also the Getting Started page of the Google API Javascript Client documentation.

另请参阅Google API Javascript客户端文档的“入门”页面。

#2


0  

Try using the header normally, but fetching the token and adding a variable containing it where you need the token to show.

尝试正常使用标题,但是获取标记并在需要标记显示的地方添加包含标记的变量。