You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Apollo-Angular中配置API密钥访问MongoDB Realm GraphQL API

在Apollo-Angular中配置MongoDB Realm GraphQL API的API密钥授权

你可以通过两种方式给Apollo客户端添加MongoDB Realm要求的API密钥授权头,完全对应你在Postman里验证过的配置逻辑:

方法1:直接在HttpLink中固定添加授权头

如果你的API密钥是固定不变的,直接在httpLink.create的配置里加入headers属性即可,把Authorization字段设置为apiKey <你的密钥>格式:

const uri = 'https://ap-south-1.aws.realm.mongodb.com/api/client/v2.0/app/myapp_with_id/graphql'; 
// 替换成你的MongoDB Realm API密钥
const API_KEY = 'your-realm-api-key-here';

export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
  return {
    link: httpLink.create({
      uri,
      headers: {
        Authorization: `apiKey ${API_KEY}`
      }
    }),
    cache: new InMemoryCache(),
  };
}

方法2:使用Context Link动态添加授权头

如果后续需要动态修改授权信息(比如切换用户令牌),可以用apollo-link-context创建一个授权链接,再和HttpLink合并:

import { setContext } from '@apollo/client/link/context';

const uri = 'https://ap-south-1.aws.realm.mongodb.com/api/client/v2.0/app/myapp_with_id/graphql'; 
const API_KEY = 'your-realm-api-key-here';

export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
  // 创建上下文链接,注入授权头
  const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        Authorization: `apiKey ${API_KEY}`
      }
    };
  });

  // 合并授权链接和HTTP链接
  const link = authLink.concat(httpLink.create({ uri }));

  return {
    link,
    cache: new InMemoryCache(),
  };
}

两种方法都能实现Postman里的授权逻辑,第一种更简单适合固定密钥场景,第二种扩展性更强,方便后续调整授权策略。

内容的提问来源于stack exchange,提问作者monzim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:03:31