我已经配置了 API-Gateway 来调用 Cloud Function,我们还为这个 API-Gateway 主机配置了负载均衡器。但是当我们从我们的 Web 应用程序调用这个负载均衡器端点时,我们面临着 CORS 问题。
问题 1:请指导我如何在 API config open-api YAML 文件中添加 CORS 支持。问题 2:如何在这个 open-api 配置 YAML 文件中添加自定义身份验证端点?
高级流程:webapp --> 负载均衡器 url --> API-Gateway --> CloudFunction
我已根据 GCP 链接在云功能中添加了 CORS 后端支持:https ://cloud.google.com/functions/docs/writing/http#authentication_and_cors
云函数代码如下:
public class Demand implements HttpFunction {
private static final Logger logger = Logger.getLogger(Demand.class.getName());
// Use GSON (https://github.com/google/gson) to parse JSON content.
private static final Gson gson = new Gson();
@Override
public void service(HttpRequest request, HttpResponse response) throws Exception {
String contentType = request.getContentType().orElse("");
logger.info(() -> "contentType: " + contentType);
// Set CORS headers
// Allows GETs from any origin with the Content-Type
// header and caches preflight response for 3600s
response.appendHeader("Access-Control-Allow-Origin", "*");
System.out.println("Added preflight options request support::::::::::");
if ("OPTIONS".equals(request.getMethod())) {
System.out.println("OPTIONS::::::::::::::::");
response.appendHeader("Access-Control-Allow-Methods", "*");
response.appendHeader("Access-Control-Allow-Headers", "Content-Type");
response.appendHeader("Access-Control-Max-Age", "3600");
response.setStatusCode(HttpURLConnection.HTTP_NO_CONTENT);
return;
}
// Handle the main request.
BufferedWriter writer = response.getWriter();
writer.write("CORS headers set successfully!");
}
以下开放 API 规范:
---
info:
description: Sample API on API Gateway with a Google Cloud Functions backend
title: trigger-post
version: 1.0.0
paths:
/triggerondemand:
post:
consumes:
- application/json
operationId: triggerondemand
parameters:
- description: triggerondemand.
in: body
name: ondemand
schema:
properties:
fileStatus:
type: string
type: object
responses:
'201':
description: Created
summary: triggerondemand
x-google-backend:
address: >-
https://us-east1-neodev-305805.cloudfunctions.net/demand
produces:
- application/json
schemes:
- https
swagger: '2.0'
浏览器报错如下:
Access to XMLHttpRequest at 'https://apitest.dev.app.com/triggerondemand' from origin 'https://dataplatform.dev.app.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
提前致谢