Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular resource how to keep ajax header and enable cors at the same time

In my ng-resource files, I enable the 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}
    })
}])

So that I can separate ajax and non-ajax request and response accordingly (to send json data like res.json(data), or to send the entire html page like res.render('a.html')

for example, in my error handler, I need to decide to render error.html page or to just send a error message:

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

But now I need to do CORS request to other sites. Is it possible to do CORS request while keeping the ajax header? or other ways I can identify ajax and non-ajax request from server?

In case my question is not clear, heres a relevant article about angular and CORS http://better-inter.net/enabling-cors-in-angular-js/

Basically, we need to delete xhr header to enable cors for other server, but I need the header for my own server

EDIT 2:

today I tried integrating google map and I got this error:

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.
like image 725
OMGPOP Avatar asked Jul 07 '15 08:07

OMGPOP


People also ask

Does Ajax need CORS?

The server must support CORS and indicate that the domain of the client making the request is permitted to do so. The beauty of this mechanism is that it is automatically handled by the browser and web application developers do not need to concern themselves with its details.

What is CORS Ajax?

CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin. Figure 2. Cross domain ajax request. When you do a cross-origin request, the browser sends Origin header with the current domain value.


1 Answers

If you are using the latest version of angular.js, you can do this

First, add xhr header (what you did was correct)

    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Then in your google map search function

var searchAddress = function(address) {
    var params = {address: address, sensor: false};
    //Note: google map rejects XHR header
    $http.get(google_map_web_api_url, {params: params, headers: {'X-Requested-With': undefined}})
        .success(function(data, status, headers, config) {
        })
        .error(function(data, status, headers, config) {
        })
}

The headers config argument passed in will delete xhr per request base, which means your ng-resource requests are untouched

like image 180
John Avatar answered Oct 02 '22 09:10

John