尽管启用了CORS,$ http angular也无法正常工作

时间:2014-11-28 03:51:05

标签: javascript angularjs apache cors

在我深入研究角度之前,我在服务器上进行了一次干净的测试,以检查我的CORS是否已启用。使用此脚本。

    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);

它可以正常工作。

enter image description here

但是当我通过$ http

使用角度时
var http = "//api.otamarket.local/api/cors.json";
return $http.post(http,credentials);

我收到此错误。

enter image description here

以下是标题回复:

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

这是我启用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>

这是端点:

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

如您所见,我在我的apache服务器的vhost中启用了CORS。它通过XHR工作,我很困惑为什么它不能在这里工作。

感谢。

3 个答案:

答案 0 :(得分:1)

我知道,使用$ http调用时,内容类型设置不正确。尝试将header属性添加到$ http调用中,如下所示,

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

})

答案 1 :(得分:0)

您的错误消息明确指出该错误与CORS无关。

它返回405,这意味着请求方法与服务器上定义的方法不匹配。

正如您在标题中看到的那样,您的请求方法是OPTIONS,而我假设您的服务器方法是专为POST设计的。

交叉检查您是否已写入任何HTTP拦截器,或者某些代码是否正在更改您的请求标头。

此外,由于您正在检索数据,为什么不使用获取请求..

请尝试使用此代码段:

$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;
      });

答案 2 :(得分:0)

Angular Preflights POST / DELETE / GET / PUT首先请求OPTIONS请求。一旦服务器成功响应,说明服务器允许哪些方法,则angular会发出PUT / POST / XXX请求。当您从Angular收到OPTIONS时,您的服务器没有响应允许的请求类型。