Dealing with a 301 and location headers for a REST

2019-08-03 07:15发布

问题:

I am using Angularjs Chrome 35.0 and Firefox 30.0.

I need to make Rest requests to an API.

Every single request which have 200,201,404 (...) as response does work well.

Some of those responses with a 301 and a location header.

my javascript

this.folder = function(folder) {
        var url = config.domain + '/' + folder.key;
        var methods = resource(url, null, {
            'move': {
                method: 'PUT',
                params: {
                    'move': ''
                },
                headers: {
                    'copy-source': '/path/to/' + folderKey
                },
                url: config.domain + '/path/to/' + newKey
            }
        });

and after the call (which does work), I have this error shown in the console :

XMLHttpRequest cannot load http://domain.com/path/to/folder?move=. The request was redirected to 'http://domain.com/path/to/folder', which is disallowed for cross-origin requests that require preflight.

EDIT

And I have an error status 0 and not really the 301. So it is impossible to deal with the response if I cannot make any difference bewteen a 301 and a 0 response...

回答1:

I did make an interceptor and checking for a specific header which should occur only in this case. It is not really proper but I guess it is the best solution...

var interceptor = ['$rootScope', '$q',
                function(scope, $q) {
                    var success = function(response) {
                        return response;
                    }

                    var error = function(response) {
                        if (response.status === 0) { // server not responding
                            if (angular.isDefined(response.config.params['move'])) {
                                response.status = 301;
                                response.genericMessage = 'Folder correctly moved';
                            } else {
                                response.genericMessage = 'Server Connection refused, is it on ?';
                                window.location = '/#/login';
                            }
                        }
                        return $q.reject(response);
                    }

                    return function(promise) {
                        return promise.then(success, error);
                    }
                }
            ];
            $httpProvider.responseInterceptors.push(interceptor);