跨域
最后更新于:2022-04-01 22:46:08
## 跨域
### [](https://github.com/bolasblack/http-api-guide#cors)CORS
接口支持[“跨域资源共享”(Cross Origin Resource Sharing, CORS)](http://www.w3.org/TR/cors),[这里](http://enable-cors.org/)和[这里](http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity)和[这份中文资料](http://newhtml.net/using-cors/)有一些指导性的资料。
简单示例:
~~~
$ curl -i https://api.example.com -H "Origin: http://example.com"
HTTP/1.1 302 Found
~~~
~~~
$ curl -i https://api.example.com -H "Origin: http://example.com"
HTTP/1.1 302 Found
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: ETag, Link, X-Total-Count
Access-Control-Allow-Credentials: true
~~~
预检请求的响应示例:
~~~
$ curl -i https://api.example.com -H "Origin: http://example.com" -X OPTIONS
HTTP/1.1 302 Found
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With
Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE
Access-Control-Expose-Headers: ETag, Link, X-Total-Count
Access-Control-Max-Age: 86400
Access-Control-Allow-Credentials: true
~~~
### [](https://github.com/bolasblack/http-api-guide#json-p)JSON-P
如果在任何 `GET` 请求中带有参数 `callback` ,且值为非空字符串,那么接口将返回如下格式的数据
~~~
$ curl http://api.example.com/#{RESOURCE_URI}?callback=foo
~~~
~~~
foo({
"meta": {
"status": 200,
"X-Total-Count": 542,
"Link": [
{"href": "http://api.example.com/#{RESOURCE_URI}?cursor=0&count=100", "rel": "first"},
{"href": "http://api.example.com/#{RESOURCE_URI}?cursor=90&count=100", "rel": "prev"},
{"href": "http://api.example.com/#{RESOURCE_URI}?cursor=120&count=100", "rel": "next"},
{"href": "http://api.example.com/#{RESOURCE_URI}?cursor=200&count=100", "rel": "last"}
]
},
"data": // data
})
~~~
';