Watch 751 Star 1.1K Fork 332

开源中国 / Gitee FeedbackRuby

Cross-Origin Request Blocked

任务
已验收
wzpan  Created at

现象描述

尝试用 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 支持即可。

905323_frech 1589129_sfatpaper total 3 participants

Comments (4)

wzpan 2017-09-02 23:11

经测试,响应头依然没有开启 CORS 支持。

905323_frech
antonius 2017-09-03 12:12

@wzpan 还没更新。

905323_frech
antonius 2017-09-07 10:19

@wzpan 已经更新。

1589129_sfatpaper
SFatpaper 2019-03-21 10:13

您好,请问目前码云是否开启了CORS支持呢?

Sign in and comment

Assignee
Labels
Not set
Project
Milestone
Branch
Scheduled start
Not set
Scheduled end
Not set
Top level
Priority

Help Search