AngularJS:$ http服务GET到php服务器:请求方法:选项,状态代码:405方法不允许

时间:2015-01-30 11:56:50

标签: angularjs get angular-http

我在这个问题上挣扎了好几个小时......: - (

我的grunt服务角度应用程序向同一主机(apache)上的简单PHP服务发出$ http GET 请求,以获取人员列表。我得到的结果是一个OPTIONS请求(???),得到405响应......但是为什么在GET之前有一个OPTIONS飞行前请求???

以下是我的设置细节:

Grunt config Gruntfile.js

grunt.initConfig({
  ...
  connect: {
    options: {
      port: 9000,
      hostname: '0.0.0.0',
      livereload: 35729
    },
  },
  ...

Angular服务 persons.js

app.service('Persons', function($http) {
  ...
  return({
    getPersons: function () {
      return $http({
        method: 'get',
        url: http://192.168.1.1/myapp/api/persons/get',
      }).then(handleSuccess, handleError);
    },
    ...
  });
  ...

文件 /api/persons/get/index.php

...
header("Access-Control-Allow-Origin", "http://192.168.1.1:9000");
header("Access-Control-Allow-Methods", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
header("Access-Control-Allow-Headers", "GET, PUT, POST, OPTIONS, DELETE, X-XSRF-TOKEN");
echo json_encode($persons);

(我实际上,服务器端我使用Slim框架,所以这是" index.php"文件,它提供" / api / persons /...&# 34;请求通过.htaccess:" ... RewriteRule ^(。)$ index.php [QSA,L]" ... *)

这是我得到的(悲伤的:-()结果:

Remote Address:192.168.1.1:80
Request URL:http://192.168.1.1/myapp/api/persons/get
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,it-IT;q=0.6,it;q=0.4,tr;q=0.2,de;q=0.2
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:192.168.1.1
Origin:http://192.168.1.1:9000
Pragma:no-cache
Referer:http://192.168.1.1:9000/
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36
Response Headersview source
Allow:GET HEAD
Connection:close
Content-Length:0
Content-Type:text/html;charset=UTF-8
Date:Fri, 30 Jan 2015 11:36:43 GMT
Server:Apache/2.2.15 (CentOS)
Set-Cookie:PHPSESSID=a5dbcfa18fcb64a29dbad999c6811d69; path=/
Set-Cookie:a5dbcfa18fcb64a29dbad999c6811d69=DEFAULT%7C0%7C2M3TMlgUx3gTlaarYzHIdD28l8q9FTcNubt55%2BUGpAo%3D%7C7456bf61db3500c8bb7b3bc38082a470ce4a2ad3; path=/
X-Powered-By:PHP/5.6.4

我也尝试使用grunt-connect-proxy,没有更好的结果......

如果我忘记了任何细节,请问......

有任何线索吗?

1 个答案:

答案 0 :(得分:1)

对于跨域请求,CORS预检是必需的。

OPTIONS调用实际上返回了可用方法列表(GET,POST等)。

您应该在php后端允许OPTIONS调用:

header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

查看CORS not working php