2 个端口上节点剩余 api 和 angularJS 应用程序的 CORS 问题

CORS issue with node rest api and angularJS app on 2 ports

我的 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 :

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

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 提供资源时非常有用。

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