我从一个JS应用程序发送:
let config = {
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: `email=${creds.email}&password=${creds.password}`
}
fetch('http://localhost:3000/sessions', config)
在我的Rails控制器中:
class SessionsController < ApplicationController
def create
@user = User.where(email: params[:email]) # this doesn't work!
end
end
我收到400条错误请求:
Started POST "/sessions" for 127.0.0.1 at 2017-08-25 23:56:56 +0200
Error occurred while parsing request parameters.
Contents:
email=hello&password=moto
ActionDispatch::Http::Parameters::ParseError
(743: unexpected token at 'email=hello&password=moto'):
任何人都可以了解如何从JS处理这些数据?
答案 0 :(得分:0)
我相信,您应该添加CSRF令牌以绕过伪造保护并将此键值添加到标题中:
'X-CSRF-Token': document.querySelector("meta[name=csrf-token]").content
否则你可以使用捆绑的rails-ujs库,它已包含此令牌:
Rails.ajax({
type: "POST",
url: "http://localhost:3000/sessions/create",
data: mydata,
success: function(repsonse){...},
error: function(repsonse){...}
})
答案 1 :(得分:0)
是的,您可以为csrf protect指定具体操作。 - &GT; DOC
os