我有一个rails 5.2应用程序,它最初是用Devise和普通的erb文件构建的。我可以在前台检查current_user等等。
现在我正试着慢慢地把它移到React前端。我没有更改任何设置,但是我的控制器的create操作对于user_signed_in?返回false,但在索引处它返回true。有没有我没有在我的请求中传递的头?
示例代码
class FanciesController < ApplicationController
skip_before_action :verify_authenticity_token, only: :search_fancy
after_action :verify_authorized
def index
@fancies = Fancy.all
authorize @fancies
respond_to do |format|
format.html { render :index }
format.json { render json: {...}, status: :ok }
end
end
def create
@fancy = Fancy.new(...)
authorize @fancy
respond_to do |format|
if @fancy.save
format.html { redirect_to @fancy, notice: 'Availability was successfully created.' }
format.json { render :show, status: :created, json: {..}}
else
format.html { render :new }
format.json { render json: {...}, status: :unprocessable_entity }
end
end
end
end前端代码:
#index.html.erb
<%= react_component("FancyScreen", { selection_fancies: @fancies }) %>react组件:
class FancyScreen extends React.Component {
...
onCreateClick(selected_time) {
const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' };
const requestOptions = {
method: 'POST',
headers: headers,
body: JSON.stringify({...})
}
fetch(curl_url, requestOptions)
.then(response => response.json())
.then(data => {
new_fancy.push(data)
fn.setState({
fancies: new_fancy
});
});
}
}
}我尝试通过我的头传递csrf令牌,但仍然不起作用。
‘X-CSRF-TOKEN’: $(‘meta[name=”csrf-token”]’).attr(‘content’)我肯定离开了,我错过了一些基本的东西,但如果有人能给我指出正确的方向,我相信我能找到答案。我尝试安装devise-jwt gem,但看起来并不是我真正想要的。
你知道我做错了什么吗?
发布于 2020-05-07 18:20:35
为了在React - Rails集成中对用户进行身份验证,您需要使用基于令牌的身份验证系统。检查devise_token_auth gem。在第一次登录rails之后,rails会向您发送client-id、token-id和uid。将它们存储在cookie中,并在每次进行API调用时在标头中发送它们。API将刷新这些值并将它们发送回前端。使用新值再次更新cookie,然后继续该过程。
https://stackoverflow.com/questions/61579187
复制相似问题