两个端口上的节点rest api和angularJS app的CORS问题

时间:2015-03-09 23:34:34

标签: angularjs node.js api rest cors

我的angularJS应用程序(在localhost:9000上)尝试捕获我的节点服务器(在localhost:9001上)时遇到了经典的CORS问题

这是我的休息api(app.js)代码:

var cors = require('cors');
app.use(cors());
app.options('*', cors());

app.all('/*', function(req, res, next) {
    // CORS headers
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header('Access-Control-Allow-Methods',    'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
    if (req.method == 'OPTIONS') {
        res.status(200);
        res.write("Allow: GET,PUT,POST,DELETE,OPTIONS");
        res.end();
    } else {
        next();
    }
});

正如你所看到的,我试过这些解决方案是徒劳的:

这是webapp中简单的$ http调用:

var req = {
    method: 'GET',
        url: 'localhost:9001/memories'
    };
    $http(req).
        success(function(data, status, headers, config) {
            // this callback will be called asynchronously
            // when the response is available
            reutrnStatus.success = true;
            reutrnStatus.msg = status;
            memories = data;
        }).
        error(function(data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
            reutrnStatus.success = false;
            reutrnStatus.msg = status;
        });

我在webapp中尝试了一些解决方案(在app.js中):

// Enable AngularJS to send its requests with the appropriate CORS headers
// globally for the whole app:
.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    /**
     * Just setting useXDomain to true is not enough. AJAX request are also
     * send with the X-Requested-With header, which indicate them as being
     * AJAX. Removing the header is necessary, so the server is not
     * rejecting the incoming request.
     **/
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

但是我已经接近放弃,因为它仍然没有用......这给了我同样的错误:

XMLHttpRequest cannot load localhost:9001/memories. Cross origin
requests are only supported for protocol schemes: http, data, chrome, 
chrome-extension, https, chrome-extension-resource.

为了完全清楚,我按照其他api的教程:

1 个答案:

答案 0 :(得分:6)

您正在向未知协议发出请求。

Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

你需要改变这个:

method: 'GET',
    url: 'localhost:9001/memories'
};

......对此:

method: 'GET',
    url: 'http://localhost:9001/memories'
};

或者,您可以将其设置为//localhost:9001/memories,并且浏览器将使用当前协议,如果您为httphttps提供资源,则该协议非常有用。

虽然不相关,但您的回调在变量名称中存在拼写错误。