简体   繁体   中英

$http angular doesn't work despite CORS enabled

Before I delve into angular, I made a clean test on my server to check if my CORS is enabled. Using this script.

    var xhr     = new XMLHttpRequest();
    var param   = 'name=mrA';
    xhr.open('POST','http://api.otamarket.local/api/cors.json',true);

    //Send the proper header information along with the request
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function () {
      if (this.status == 200 && this.readyState == 4) {
        console.log('response: ' + this.responseText);
      }
    };
    xhr.send(param);

It works just fine as you can see.

在此处输入图片说明

But when I used angular via $http

var http = "//api.otamarket.local/api/cors.json";
return $http.post(http,credentials);

I get this error.

在此处输入图片说明

Here is the header response:

Remote Address:127.0.0.1:80
Request URL:http://api.otamarket.local/api/cors.json
Request Method:OPTIONS
Status Code:405 Method Not Allowed

Request Headers view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.otamarket.local
Origin:http://otakuket.local
Referer:http://otakuket.local/
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36

Response Headersview source
Access-Control-Allow-Origin:*
Connection:Keep-Alive
Content-Length:0
Content-Type:text/html
Date:Fri, 28 Nov 2014 03:47:31 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.9 (Win32) OpenSSL/1.0.1g PHP/5.5.11
X-Powered-By:PHP/5.5.11

Here is where I enabled CORS

<VirtualHost *:80>
    DocumentRoot "C:\Users\aldri_000\SkyDrive\Program  Experiment\websites\api.otamarket.local\public"
    ServerName api.otamarket.local
    Header set Access-Control-Allow-Origin "*"
<Directory "C:\Users\aldri_000\SkyDrive\Program Experiment\websites\api.otamarket.local">
    Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Order Deny,Allow
        Allow from all
        Require all granted
</Directory>
</VirtualHost>

Here is the endpoint:

public function post_cors()
{
   $rsp            = array();
   $rsp['rsp']     = 'CORS Work';
   return $this->response($rsp);
}

As you can see, I had enabled CORS in the vhost of my apache server. It works via XHR and I am puzzled as to why it doesn't work here.

Thanks.

i see, content-type is not set properly when using $http call. try adding headers property to your $http call like this,

$http({
method: 'POST',
url: url,
data: $.param({fkey: "key"}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}

})

Your error Message clearly states that the error is not associated with CORS.

It's returning 405, which means that the request method doesn't matches with the one that is been defined on the server.

As you see in your headers, Your request method is OPTIONS, whereas i assume that your server method has been designed for POST.

Cross Check if you have any HTTP interceptors written or if some piece of code is changing your request header.

Also, since you're retrieving data, why not use Get Request ..

Try this snippet instead :

$http({method: 'GET', url: '//api.otamarket.local/api/cors.json'}).
        success(function(data, status) {
          $scope.status = status;
          $scope.data = data;
        }).
        error(function(data, status) {
          $scope.data = data || "Request failed";
          $scope.status = status;
      });

Angular Preflights POST/DELETE/GET/PUT requests with an OPTIONS request first. Upon a successful response from the server stating what methods are allowed by the server, angular then makes the PUT/POST/XXX request. Your server isn't responding with allowed request types when it receives OPTIONS from Angular.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM