如何在GraphQL/AWS Amplify中启用前端CORS模式?
如何对AWS Amplify的GraphQL执行同样的操作?
fetch('https://trusted-api.co.jp', {
mode: 'cors'
});
我既没有找到如何操作的文档,也没有找到提到CORS的源代码。
参考
常规的GraphQL操作可以调用如下:
import AWSAmplifyAPI, { graphqlOperation as graphQL_Operation, GraphQLResult } from "@aws-amplify/api";
import Observable from "zen-observable";
export default class DataBaseService {
public static async sendRequestAndExtractDataFromResponse(
graphQL_RawRequest: string,
requestVariables?: object
): Promise<unknown> {
const serverRawResponse: GraphQLResult | Observable<unknown> =
await AWSAmplifyAPI.graphql(graphQL_Operation(graphQL_RawRequest, requestVariables));
// ...
}
}
解决方案
您需要在服务器端配置此问题,因此服务器端需要批准此问题。
从技术上讲,您的Amplify lambda函数将添加类似以下内容的代码:
exports.handler = async (event) => {
const response = {
statusCode: 200,
// Uncomment below to enable CORS requests
headers: {
"Access-Control-Allow-Origin": "*",
},
// headers: {
// "Access-Control-Allow-Headers" : "Content-Type",
// "Access-Control-Allow-Origin": "https://www.example.com",
// "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
// },
body: JSON.stringify("Hello from Lambda!"),
};
return response;
};
相关文章