2

我有一个简单的 Rails 4.1.4 应用程序,我正在尝试将单独主机上的 AngularJS 应用程序连接到它的 API。虽然我访问它没有问题,但 Rails 似乎认为请求是 HTML 并忽略 Content-Type: 'application/json'

Started GET "/api/v1/locations?access_token=xxx&headers=%7B%22Content-type%22:%22application%2Fjson%22%7D" for 127.0.0.1 at 2014-09-03 17:12:11 +0100
Processing by Api::V1::LocationsController#index as HTML
Parameters: {"access_token"=>"xxx", "headers"=>"{\"Content-type\":\"application/json\"}"}

在我的 NG 应用程序中,我尝试了多种标头组合,包括:

app.factory('Location', ['$resource', "$localStorage",
  function($resource, $localStorage){
    return $resource('http://my-api.com/api/v1/locations/', {headers:{'Content-type' : 'application/json'}}, {
      query: {
        method: 'GET',
        headers: {'Content-type': 'application/json'},
        isArray: true,
        dataType: 'json',
        params: { access_token: $localStorage.accessToken }
      }...

NG 端的响应看起来不错,尽管在我的位置控制器中只有这个,但它用 JSON 响应:

class Api::V1::LocationsController < Api::V1::BaseController

  doorkeeper_for :all
  before_filter :authorize
  respond_to :json

  def index
   @locations = @current_user.locations.order("created_at desc").limit(5)
   respond_with @locations
  end

end

我还设置(并测试未设置)cors 标题。

我在某处读到,如果其中有正斜杠,Rails 将不会读取内容类型标题...

虽然这似乎不会导致很多问题,但我确实认为它会干扰作为应用程序一部分的 Doorkeeper。

4

1 回答 1

5

这不是 Rails 问题。原来我需要在 NG 配置中摆弄一些标题等。

我将以下内容添加到 app.js

$httpProvider.defaults.useXDomain = true;
// $httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";

第二行抛出了一个错误,但我已经留在那里了。

于 2014-09-10T00:54:26.410 回答