在我的 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/