代码拉取完成,页面将自动刷新
尝试用 AJAX 调 OSChina 的 api,遇到 CORS 错误:
XMLHttpRequest cannot load http://git.oschina.net/api/v5/repos/wzpan/comment/issues?page=1&_=1498968376528. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access.
写一个简单的 AJAX 请求即可复现本问题。测试代码片段地址:https://git.oschina.net/wzpan/8wb4a23cfiosp7knd5zhu41.code.git
在本地用浏览器打开,开启调试窗口,可以看到红色的错误提示:
cURL -i
发起 API 请求,从返回的头部信息可以看到后台并未设置 Access-Control-Allow-Origin
头部信息:
$ curl -i 'http://git.oschina.net/api/v5/repos/wzpan/hexo-theme-freemind-blog/issues/1'
HTTP/1.1 200 OK
Date: Sun, 02 Jul 2017 04:37:59 GMT
Content-Type: application/json
Content-Length: 5039
Connection: keep-alive
Set-Cookie: aliyungf_tc=AQAAAFoYlVfFxwsAtfj7OuNXQkQRrERJ; Path=/; HttpOnly
Server: nginx
Status: 200 OK
X-UA-Compatible: IE=Edge,chrome=1
ETag: "0864cec3633609f9670ebb69db0ba927"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: a94eb6414741f01a9269e4cb0ef3cf47
X-Runtime: 0.038748
X-Rack-Cache: miss
作为参考, Github 是支持 CORS 的:
~ curl -i "https://api.github.com/repos/wzpan/hexo-theme-freemind-blog/issues/1"
HTTP/1.1 200 OK
Date: Sun, 02 Jul 2017 04:39:56 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 1840
Server: GitHub.com
Status: 200 OK
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 57
X-RateLimit-Reset: 1498973430
Cache-Control: public, max-age=60, s-maxage=60
Vary: Accept
Last-Modified: Sat, 01 Jul 2017 15:27:54 GMT
X-GitHub-Media-Type: github.v3; format=json
Access-Control-Expose-Headers: ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
Access-Control-Allow-Origin: * # 这里开启了 CORS 支持
Content-Security-Policy: default-src 'none'
Strict-Transport-Security: max-age=31536000; includeSubdomains; preload
X-Content-Type-Options: nosniff
X-Frame-Options: deny
X-XSS-Protection: 1; mode=block
X-Runtime-rack: 0.041204
Vary: Accept-Encoding
X-Served-By: e14705a23c085afeff5e104b1fc3922a
Vary: Accept-Encoding
X-GitHub-Request-Id: 9538:C1E5:3C13D9:51772E:5958791C
因此,解决方案是在后断响应头加入 Access-Control-Allow-Origin: *
,开启 CORS 支持即可。