javascript – Access-Control-Allow-Origin和Angular.js $http

每当我做一个webapp,我得到一个CORS问题,我开始做咖啡。拧了一会儿,我设法得到它的工作,但这一次,它不是,我需要帮助。

这里是客户端代码:

$http({method: 'GET', url: 'http://localhost:3000/api/symbol/junk', 
            headers:{
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
                'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With',
                'X-Random-Shit':'123123123'
            }})
        .success(function(d){ console.log( "yay" ); })
        .error(function(d){ console.log( "nope" ); });

服务器端是一个普通的node.js和一个快速的应用程序。我有一个扩展名为cors,它正在以这种方式使用:

var app = express();
app.configure(function(){
  app.use(express.bodyParser());
  app.use(app.router);
  app.use(cors({origin:"*"}));
});
app.listen(3000);

app.get('/', function(req, res){
    res.end("ok");
});

如果我做

curl -v -H "Origin: https://github.com" http://localhost:3000/

它回来:

* Adding handle: conn: 0x7ff991800000
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7ff991800000) send_pipe: 1, recv_pipe: 0
* About to connect() to localhost port 3000 (#0)
*   Trying ::1...
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.30.0
> Host: localhost:3000
> Accept: */*
> Origin: https://github.com
>
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Date: Tue, 24 Dec 2013 03:23:40 GMT
< Connection: keep-alive
< Transfer-Encoding: chunked
<
* Connection #0 to host localhost left intact
ok

如果我运行客户端代码,它制定了这个错误:

OPTIONS http://localhost:3000/api/symbol/junk No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. angular.js:7889
XMLHttpRequest cannot load http://localhost:3000/api/symbol/junk. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. localhost/:1
nope 

检查Chromes标题:

Request URL:http://localhost:3000/api/symbol/junk
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,es;q=0.6,pt;q=0.4
Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-methods, access-control-allow-headers, x-random-shit
Access-Control-Request-Method:GET
Cache-Control:max-age=0
Connection:keep-alive
Host:localhost:3000
Origin:http://localhost:8000
Referer:http://localhost:8000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Response Headersview source
Allow:GET
Connection:keep-alive
Content-Length:3
Content-Type:text/html; charset=utf-8
Date:Tue, 24 Dec 2013 03:27:45 GMT
X-Powered-By:Express

检查请求头我看到我的测试字符串X-Random-Shit存在于“Access-Control-Request-Headers”中,但它的值不存在。另外,在我的头,我期望看到一个线为我设置的每个标题,而不是一个blob。

更新 – –

我改变了我的前端jQuery,而不是Angular,并使我的后端像这样:

var app = express();
app.configure(function(){
  app.use(express.bodyParser());
  app.use(app.router);
});
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
    if ('OPTIONS' == req.method){
        return res.send(200);
    }
    next();
});

app.get('/', function(req, res){
    res.end("ok");
});

现在它使用GET,但不与任何其他(PUT,POST ..)。

我会看看你是否有任何一个解决方案。在同一时间把RESTful概念抛出窗口,并使一切与GETs。

最佳答案
我是新来的AngularJS和我碰到这个CORS问题,几乎失去了我的心!幸运的是,我发现了一种方法来解决这个问题。所以这里它….

我的问题是,当我使用AngularJS $ resource发送API请求我得到这个错误消息XMLHttpRequest不能加载http://website.com。在所请求的资源上没有“Access-Control-Allow-Origin”头。因此,’http:// localhost’不允许访问。 Yup,我已经添加了callback =“JSON_CALLBACK”,它没有工作。

我做了什么来解决它的问题,而不是使用GET方法或诉诸于$ http.get,我使用JSONP。只需用JSONP替换GET方法,并将api响应格式更改为JSONP。

    myApp.factory('myFactory', ['$resource', function($resource) {

           return $resource( 'http://website.com/api/:apiMethod',
                        { callback: "JSON_CALLBACK", format:'jsonp' }, 
                        { 
                            method1: { 
                                method: 'JSONP', 
                                params: { 
                                            apiMethod: 'hello world'
                                        } 
                            },
                            method2: { 
                                method: 'JSONP', 
                                params: { 
                                            apiMethod: 'hey ho!'
                                        } 
                            }
            } );

    }]);

我希望有人认为这有帮助。 🙂

转载注明原文:javascript – Access-Control-Allow-Origin和Angular.js $http - 代码日志