如何让Angular和Rails交互?未知格式错误

How to make Angular and Rails interact? Unknown format error

我的 first 项目中包含 ngResource 指令,以便能够与 RESTful API.

进行交互

然后我这样设置我的工厂:

angular.module('app').factory('User', [
  '$resource', function($resource) {
    return $resource('/api/user_login/:id', { id: '@id' }, {
      update: { method: 'PUT' }
    });
  }
]);

在我的控制器中,我尝试保存用户,即发送 POST 请求。

app.controller('loginCtrl', [
  '$scope', 'User', function($scope, User) {
    return User.save();
  }
]);

我的 second 项目的控制器如下所示。我正在尝试引用创建操作。

class UserSessionsController < UserApplicationController
  respond_to :js, only: :create

  def create
    if @counterparty
      session[:counterparty_id] = @counterparty.id
      @counterparty.update(signed_in: true)
    else
      flash.now[:error] = 'Invalid email or password'
    end

    respond_with(@counterparty, layout: false)
  end
end

结果我得到 ActionController::UnknownFormat。

Started POST "/user_login" for 127.0.0.1 at 2016-02-18 16:04:58 +0200
Started POST "/user_login" for 127.0.0.1 at 2016-02-18 16:04:58 +0200
Processing by UserSessionsController#create as HTML
Processing by UserSessionsController#create as HTML
  Counterparty Load (0.3ms)  SELECT  `counterparties`.* FROM `counterparties`  WHERE `counterparties`.`email` IS NULL AND `counterparties`.`password` IS NULL LIMIT 1
  Counterparty Load (0.3ms)  SELECT  `counterparties`.* FROM `counterparties`  WHERE `counterparties`.`email` IS NULL AND `counterparties`.`password` IS NULL LIMIT 1
Completed 406 Not Acceptable in 1ms
Completed 406 Not Acceptable in 1ms

ActionController::UnknownFormat (ActionController::UnknownFormat):
  app/controllers/user_sessions_controller.rb:13:in `create'

我该如何解决这个问题?

改变 respond_to :js, only: :createrespond_to :json, only: :create

用户工厂正在做一个 json 格式的请求,虽然控制器应该响应对 op 不起作用的 js(json 包括),所以有必要设置 respond_to json 显式

用以下函数替换创建函数

    def create
      respond_to do |format|
       if @counterparty
         session[:counterparty_id] = @counterparty.id
         @counterparty.update(signed_in: true)
         format.json  { render :json => @counterparty.to_json ,status: :ok}
       else
         format.json  { render :json => 'Invalid email or password',status: :unprocessable_entity}
       end
      end
   end