【问题标题】:Angular $resource doesn't change methodAngular $resource 不会改变方法
【发布时间】:2026-02-07 08:05:01
【问题描述】:

我正在尝试使用 Angular.js 和 Couchdb 配置一个简单的服务

var App = angular.module('myapp', ['ngResource'], function(){});

App.factory('products', ['$resource', function($resource) { 

  var Products = $resource(
      'http://localhost\\:5984/products/_all_docs',
      {},
      { all: { method: 'GET'} }
  );

  return {
    all: function() {
        return Products.all();
    }
  };
}]);

当我从控制器调用 products.all() 时,我总是得到

请求标头

OPTIONS /productos/_all_docs HTTP/1.1
Host: localhost:5984
Connection: keep-alive
Access-Control-Request-Method: GET
Pragma: no-cache
Cache-Control: no-cache
Origin: http://localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17
Access-Control-Request-Headers: accept, origin, x-requested-with
Accept: */*
DNT: 1
Referer: http://localhost:8000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: es-419,es;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

响应标头

HTTP/1.1 405 Method Not Allowed
Server: CouchDB/1.2.1 (Erlang OTP/R14B04)
Date: Tue, 29 Jan 2013 22:15:31 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 69
Cache-Control: must-revalidate
Allow: GET,HEAD,POST

Request URL:http://localhost:5984/productos/_all_docs
Request Method:OPTIONS
Status Code:405 Method Not Allowed

我无法想象为什么它会在我没有声明的时候发送一个 OPTIONS 方法!

【问题讨论】:

    标签: angularjs couchdb httprequest


    【解决方案1】:

    OPTIONS 方法来自于做一个跨域请求。见Why am I getting an OPTIONS request instead of a GET request?。即使主机和请求都是到localhost,端口是不同的(5984、8000)。见Same origin host, different ports in JS

    【讨论】:

    • 那我该如何回避呢?