使用代理以绕过MongoDB Atlas上的GraphQL的跨域限制
总结
如果从在GitHub Pages上发布的静态内容中调用MongoDB Atlas的GraphQL,可以通过MongoDB Atlas的Bearer认证来避免跨域限制。然而,通过Bearer认证获取的访问令牌需要每30分钟更新一次。
作为另一种避免方法,尝试使用代理将GitHub页面和MongoDB Atlas显示在同一域名下,以绕过跨域限制。

我尝试了一种类似的组织结构。在Lambda中间插入了一个,因为直接从CloudFront到Mongodb Atlas的连接出现了错误,而且一时无法解决。

创建调用GraphQL的Lambda函数
我使用了内置了Fetch API的Node v18。在创建Lambda后,为了CloudFront的源注册,我生成了Lambda函数的URL。
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
const bound = JSON.parse(event.body);
const queryMsg = `query {
webcams(query:{status:"active",location:{
longitude_lt:${bound.longitude_lt},
longitude_gte:${bound.longitude_gte},
latitude_lt:${bound.latitude_lt},
latitude_gte:${bound.latitude_gte}}}
,limit:200
,sortBy:ID_ASC) {
id
title
location{
latitude
longitude
}
player{
day{
available
link
}
}
image{
current{
thumbnail
}
}
}
}`;
try {
const response = await fetch('https://realm.mongodb.com/api/client/v2.0/app/webcamql-qrkjj/graphql', {
method: 'POST',
headers: {
'apikey': '<apikey>' ,
'Content-Type': 'application/json'
},
body: JSON.stringify({
query: queryMsg
})
});
const webcamsJson = await response.json();
return {
statusCode: 200,
body: JSON.stringify(webcamsJson.data.webcams),
};
} catch (err) {
console.log(err);
return {
statusCode: 500,
body: JSON.stringify({
message: 'some error happened',
}),
};
}
};
CloudFront配置设置


如果使用Lambda,反应速度会变慢,而且在AWS中也不会免费。