ajax - Angular资源如何保留ajax header 并同时启用cors

标签 ajax angularjs node.js express xmlhttprequest

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

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}
    })
}])

这样我就可以相应地分离 ajax 和非 ajax 请求和响应(发送 res.json(data) 之类的 json 数据,或发送 res.json 之类的整个 html 页面。渲染('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')
    }
}

但现在我需要向其他网站发出 CORS 请求。是否可以在保留 ajax header 的同时进行 CORS 请求?或其他方式我可以识别来自服务器的 ajax 和非 ajax 请求?

如果我的问题不清楚,这里有一篇关于 Angular 和 CORS 的相关文章 http://better-inter.net/enabling-cors-in-angular-js/

基本上,我们需要删除 xhr header 才能为其他服务器启用 cors,但我需要自己的服务器的 header

编辑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.

最佳答案

Setting custom headers on XHR requests triggers a preflight request.

因此,它不会禁用 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

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

关于ajax - Angular资源如何保留ajax header 并同时启用cors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31263795/

相关文章:

javascript - formData - AJAX - PHP - 上传多个文件

javascript - 当页面上有多个相同的 ajax 调用时,如何加快我的 Ajax 调用速度?

json - 带有嵌套json对象的Angular ng-repeat?

angularjs - ui-bootstrap 分页在初始化时重置当前页面

javascript - 使用 WebStorm 时未解析的变量架构

php - AJAX 返回数据淡入现有元素

javascript - 调用 Provider 模块的 $get 中的函数会导致 TypeError

javascript - 如何调试 Grunt Mocha 任务?

javascript 'hex' 未知行为

javascript - 在 ASP.NET MVC 中将 HTML 表单数据从 View 传递到 Controller