我从 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 Controller 中:
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 的数据吗?
最佳答案
我认为,您应该添加 CSRF token 来绕过伪造保护,并将此键值添加到您的 header 中:
'X-CSRF-Token': document.querySelector("meta[name=csrf-token]").content
否则你可以使用捆绑的rails-ujs库,它已经包含了这个 token :
Rails.ajax({
type: "POST",
url: "http://localhost:3000/sessions/create",
data: mydata,
success: function(repsonse){...},
error: function(repsonse){...}
})
关于javascript - 如何在 Ruby on Rails 应用程序中接受(并解析)www-url 编码的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45890012/