腾讯云API网关跨域预检请求实现示例

腾讯云API网关默认不支持跨域访问CORS功能,如要需要支持跨域访问CORS,请先在API网关管理控制台开启CORS并重新发布API,同时按照预检请求原理的描述创建预检API。
 
1.  浏览器发送携带Origin的API请求:
 
OPTIONS / HTTP/1.1
 
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.170 Safari/537.36
 
Host: pinganyun.com
 
Accept: */*
 
Origin: http://www.Server-test.com
 
Access-Control-Request-Method: PUT
 
Access-Control-Request-Headers: PA-AG-AppId, PA-AG-Timestamp
 
•   Origin:请求的来源。
 
•   Access-Control-Request-Method:浏览器实际的请求方法。
 
•   Access-Control-Request-Headers:实际请求中额外携带的请求头信息。
 
2.  后端服务器是否允许发送跨域请求的响应信息:
 
HTTP/1.1 200 OK
 
Date: Tue, 21 Jan 2019 21:15:13 GMT
 
Content-Type: application/json
 
Access-Control-Allow-Origin: http://www.Server-test.com
 
Access-Control-Allow-Headers: PUT
 
Access-Control-Allow-Methods: PA-AG-AppId, PA-AG-Timestamp
 
•   Access-Control-Allow-Origin:允许跨域访问的源。取值为*,表示后端服务器接受任意域的请求。
 
•   Access-Control-Allow-Methods:允许浏览器使用的请求方法。
 
•   Access-Control-Allow-Headers:允许浏览器在请求中携带的请求头。
 
3.  API网关是否允许发送跨域请求的响应信息:
 
HTTP/1.1 200 OK
 
Date: Tue, 21 Jan 2019 21:15:13 GMT
 
Content-Type: application/json
 
Access-Control-Allow-Origin: http://www.Server-test.com
 
Access-Control-Allow-Headers: PUT
 
Access-Control-Allow-Methods: PA-AG-AppId, PA-AG-Timestamp
 
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
 
Access-Control-Allow-Origin: http://www.Server-test.com
 
Access-Control-Max-Age: 1800
 
•   Access-Control-Allow-Origin:允许跨域访问的源。取值为*,表示后端服务器接受任意域的请求。
 
•   Access-Control-Allow-Methods:允许浏览器使用的请求方法。
 
•   Access-Control-Allow-Headers:允许浏览器在请求中携带的请求头。
 
•   Access-Control-Max-Age:预检响应的有效时间,单位:秒。在有效期内,浏览器无需再次发送预检请求。
 
如果后端服务器返回的结果中没有以上4个字段,或仅包含其中的几个字段,API网关会补齐剩余字段后返回给浏览器。
 
4.  浏览器发送携带Origin的API请求:
 
PUT /putUser HTTP/1.1
 
Host: pinganyun.com
 
Orgin: http://www.Server-test.com
 
Content-type: application/x-www-form-urlencoded; charset=utf-8
 
Accept: application/json; charset=utf-8
 
Date: Tue, 21 Jan 2019 21:15:13 GMT
 
5.  后端服务器返回的响应信息:
 
HTTP/1.1 200 OK
 
Date: Tue, 21 Jan 2019 21:15:13 GMT
 
Content-Type: application/json
 
Content-Length: 25
 
Access-Control-Allow-Origin: http://www.Server-test.com

{"ret":"0", "msg":"succ"}
 
6.  API网关发送给浏览器的响应信息:
 
HTTP/1.1 200 OK
 
Date: Tue, 21 Jan 2019 21:15:13 GMT
 
Content-Type: application/json
 
Access-Control-Allow-Origin: http://www.Server-test.com
 
Access-Control-Allow-Headers: PUT
 
Access-Control-Allow-Methods: PA-AG-AppId, PA-AG-Timestamp
 
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
 
Access-Control-Allow-Origin: http://www.Server-test.com
 
Access-Control-Max-Age: 1800
 
Content-Length: 25
 
{"ret":"0", "msg":"succ"}