简体   繁体   English

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

[英]$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. 在深入探讨角度之前,我先在服务器上进行了干净测试,以检查是否启用了CORS。 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 但是当我通过$ http使用angular时

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 这是我启用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. 如您所见,我已经在apache服务器的虚拟主机中启用了CORS。 It works via XHR and I am puzzled as to why it doesn't work here. 它通过XHR运行,为什么在这里不起作用我感到困惑。

Thanks. 谢谢。

i see, content-type is not set properly when using $http call. 我看到,使用$ http调用时content-type设置不正确。 try adding headers property to your $http call like this, 尝试像这样在您的$ http调用中添加headers属性,

$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. 您的错误消息明确指出该错误与CORS不相关。

It's returning 405, which means that the request method doesn't matches with the one that is been defined on the server. 返回405,这意味着request方法与服务器上定义的方法不匹配。

As you see in your headers, Your request method is OPTIONS, whereas i assume that your server method has been designed for POST. 如您在标题中所看到的,您的请求方法是OPTIONS,而我假设您的服务器方法是为POST设计的。

Cross Check if you have any HTTP interceptors written or if some piece of code is changing your request header. 交叉检查是否编写了任何HTTP拦截器,或者是否有一段代码正在更改请求标头。

Also, since you're retrieving data, why not use Get Request .. 另外,由于要检索数据,所以为什么不使用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. Angular Preflights POST / DELETE / GET / PUT请求首先带有OPTIONS请求。 Upon a successful response from the server stating what methods are allowed by the server, angular then makes the PUT/POST/XXX request. 在服务器成功响应并指出服务器允许的方法后,angular然后发出PUT / POST / XXX请求。 Your server isn't responding with allowed request types when it receives OPTIONS from Angular. 您的服务器从Angular接收OPTIONS时未响应允许的请求类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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