本文介绍了跨域资源共享的基本知识,以及如何避免云函数上 Serverless web API 的问题
![a6103f96f58bf6c709f992dd6b7286ca.png](https://img-blog.csdnimg.cn/img_convert/a6103f96f58bf6c709f992dd6b7286ca.png)
构建 Web API 是 Serverless 应用中最流行的用例之一,您能在不增加其他操作开销的情况下,获得简单、可扩展的后端优势。
然而,如果您的网页正在调用后端 API,那么必须处理 跨域资源共享 (CORS) 的问题 ,如果您的网页向与您当前所在域的不同域发出 HTTP 请求,则它必须是 CORS 友好的。
如果您发现以下错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource
那么本文可能对您有所帮助。
接下来,我们将介绍 Serverless + CORS 的相关信息,目录如下:
- 预检请求 (Preflight requests)
- 响应头 (Response headers)
- CORS with cookie credentials
TL;DR
快速开始 如果您想快速解决 Serverless 应用中的 CORS,可以执行以下操作:
- 要处理 preflight requests,在每个 HTTP 端点中添加 enableCORS: true 和 integratedResponse: true 标记:
# serverless.ymlservice: products-serviceprovider: name: tencent region: ap-guangzhou runtime: Nodejs8.9 # Nodejs8.9 or Nodejs6.10plugins: - serverless-tencent-scffunctions: getProduct: handler: handler.getProduct events: - apigw: name: api parameters: path: /product stageName: release # 修改成你的 API 服务 ID serviceId: service-xxx httpMethod: GET # 开启集成相应,这里必须开启,才能自定义响应 headers integratedResponse: true, # 开启 CORS enableCORS: true createProduct: handler: handler.createProduct events: - apigw: name: api parameters: path: /product stageName: release # 修改成你的 API 服务 ID service