allow-control-allow-origin:*作为回应出现,但仍显示为erorr

时间:2015-11-28 22:17:20

标签: jquery angularjs http http-headers cors

API响应中存在

allow-control-allow-origin : *标头,但浏览器仍显示错误。网络403错误。

这是来自API的示例响应标头:

Access-Control-Allow-Headers: Origin,X-Requested-With,X-CSRF-Token,Content-Type
Access-Control-Allow-Methods: GET,POST,PUT,DELETE
Access-Control-Allow-Origin: *
Cache-Control: no-cache="set-cookie"
Connection: keep-alive
Content-Length: 870
Content-Type: text/plain;charset=UTF-8
Date: Sat, 28 Nov 2015 17:56:46 GMT
Server: Apache-Coyote/1.1
Set-Cookie: AWSELB=6B492DE10EE

Firebug中的错误:

"NetworkError: 403 Forbidden - https://xyz.....s"

 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xyz..... (Reason: CORS header 'Access-Control-Allow-Origin' missing).

请求 - AngularJS

var config = {
                headers: {
                    "Accept": "application/json",
                    "Content-Type": "application/json",
                    "Apikey": "*************" 
                }
            }

            $http.post(URL, data, config)
            .success(function (data, status, headers, config) {
               //function
            })

1 个答案:

答案 0 :(得分:3)

确保您的服务器支持OPTIONS动词并在客户端使用它时返回正确的CORS标头 - 这称为飞行前请求。看一下客户端和服务器here之间完整CORS交换的示例。

所以第一步是客户端使用OPTIONS HTTP动词发送转机前请求:

OPTIONS /canvas/73/source HTTP/1.1
Host: jsbin.com
Access-Control-Request-Method: GET
Origin: http://jsconsole.com
Access-Control-Request-Headers: x-requested-with

现在您的服务器应该使用正确的CORS标头进行响应:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With

就是这样,你已经建立了握手,现在随时可以获得你想要的任何东西:

GET /canvas/73/source HTTP/1.1
Host: jsbin.com
x-requested-with: XMLHttpRequest

并且您将获得成功回复:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Length: 977

...

您还可以查看this example