我的第一个项目中包含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();
}
]);
我的第二个项目的控制器如下所示。我正在尝试引用创建操作。
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'
我该如何解决这个问题?
答案 0 :(得分:2)
更改
respond_to :js, only: :create
至
respond_to :json, only: :create
用户工厂正在以json格式执行请求,尽管控制器应该响应不适用于op的js(包括json),因此有必要明确设置respond_to json
答案 1 :(得分:1)
用以下功能替换create function
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