Angular资源如何保持ajax头并同时启用cors

OMG*_*POP 14 ajax xmlhttprequest node.js express angularjs

在我的ng-resource文件中,我启用了ajax标头:

var app = angular.module('custom_resource', ['ngResource'])

app.config(['$httpProvider', function($httpProvider) {
    //enable XMLHttpRequest, to indicate it's ajax request
    //Note: this disables CORS
    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}])

app.factory('Article', ['$resource', function($resource) {
    return $resource('/article/api/:articleId', {articleId: '@_id'}, {
        update: {method: 'PUT'},
        query: {method: 'GET', isArray: true}
    })
}])
Run Code Online (Sandbox Code Playgroud)

这样我就可以相应地分离ajax和非ajax请求和响应(发送json数据res.json(data),或者像发送整个html页面一样res.render('a.html')

例如,在我的错误处理程序中,我需要决定呈现error.html页面或只发送错误消息:

exports.finalHandler = function(err, req, res, next) {
    res.status(err.status || 500)
    var errorMessage = helper.isProduction() ? '' : (err.message || 'unknown error')

    if (req.xhr) {
        res.json({message: errorMessage})
    }
    else {
        res.render(dir.error + '/error_page.ejs')
    }
}
Run Code Online (Sandbox Code Playgroud)

但现在我需要向其他网站提出CORS请求.是否可以在保留ajax标头的同时执行CORS请求?或其他方式我可以从服务器识别ajax和非ajax请求?

如果我的问题不明确,请参阅有关角度和CORS的相关文章 http://better-inter.net/enabling-cors-in-angular-js/

基本上,我们需要删除xhr标头以启用其他服务器的cors,但我需要我自己的服务器的标头

编辑2:

今天我尝试整合谷歌地图,我收到此错误:

XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/geocode/json?address=Singapore&sensor=false. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.
Run Code Online (Sandbox Code Playgroud)

Rah*_*bub 1

在 XHR 请求上设置自定义标头会触发预检请求。

因此,它不会禁用 CORS,但您的服务器很可能不处理预检请求。

受到这篇文章的启发:https://remysharp.com/2011/04/21/getting-cors-working

解决方案应该是使用该cors模块并将以下内容添加到您的 node.js 代码中的路由之前:

var corsOptions = {
    origin: true,
    methods: ['GET', 'PUT', 'POST'],
    allowedHeaders: ['X-Requested-With','Content-Type', 'Authorization']
};

app.options('*', cors(corsOptions)); //You may also be just fine with the default options
Run Code Online (Sandbox Code Playgroud)

您可以在以下位置阅读更多内容:https://github.com/expressjs/cors