AngularJS, PHP Restful Cors issue

2019-02-15 10:54发布

问题:

I have an issue trying to make an $http call to my rest php server. I'm doing cross domain calls from the client to the backend.

From within my Angular app this is how the $http service is configured:

.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('httpResponseInterceptor');
    $httpProvider.interceptors.push('httpTimeStampMarker');
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    delete $httpProvider.defaults.headers.common['Content-Type, X-Requested-With'];
}])

This is how the actual $http.post() is configured:

    // Set the headers
    var headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '*'
    };

    return $http({
            method: "POST",
            url: base_url,
            data: $.param(args),
            headers: headers
        })
        .success(function(data, status) {

        })
        .error(function(data, status) {

        });

This is the .htaccess of the server:

# Cors
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Methods"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

The preflight request goes fine:

**Request headers:**
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-methods, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:***
Origin:***
Referer:***
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36

**Response headers**
Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Methods
Access-Control-Allow-Methods:PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Allow:OPTIONS,GET,HEAD,POST
Connection:Keep-Alive
Content-Length:0
Content-Type:httpd/unix-directory
Date:Fri, 26 Dec 2014 07:12:24 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.9 (Unix) PHP/5.6.2

However the actual post request fails:

XMLHttpRequest cannot load http://***/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '***' is therefore not allowed access. The response had HTTP status code 404.

These are the request and response headers:

**Request headers**
    Accept:*
    Accept-Encoding:gzip, deflate
    Accept-Language:en-US,en;q=0.8
    Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT
    Access-Control-Allow-Origin:*
    Connection:keep-alive
    Content-Length:130
    Content-Type:application/x-www-form-urlencoded
    Host:***
    Origin:http://***
    Referer:***
    User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36


**Response headers**
Connection:Keep-Alive
Content-Length:198
Content-Type:text/html; charset=iso-8859-1
Date:Fri, 26 Dec 2014 07:12:24 GMT
Keep-Alive:timeout=5, max=99
Server:Apache/2.4.9 (Unix) PHP/5.6.2

I'm obviously missing some headers in the response off the post request.

However the issue it's failing on does work in the preflight request. I've tried adding some headers in the index.php of the rest server, but the request doesn't arrive there and gets stuck earlier (I'm guessing when the .htaccess is loaded).

What am I missing here?

回答1:

After a few hours I finally found it out.

My .htaccess:

# Cors
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin"
Header always set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

The hint @Alexey Rodin gave was almost the right one. Instead of changing "add" to "set" it should be set to "always set".

This site helped me out:

Regarding AngularJS, I can confirm that no other settings are needed for CORS to work. So Angular's $http does not need the be changed with headers or so, the default settings should work with the .htaccess entries stated above.



回答2:

Try to use set instead add on your .htaccess

Header set Access-Control-Allow-Origin "*"

See more here