[英]Rails 4: Set a cookie in a request/response if type is JSON?
如何在Rails中響應application / json類型的請求時設置cookie?
控制器操作按預期工作,但沒有設置cookie,並且響應中沒有Set-Cookie標頭。 任何幫助將不勝感激。
控制器:
class SessionsController < ApplicationController
def create
@user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in(user)
.
.
cookies[:test] = 'Test cookie'
render json: @user
#render json: @user, set_cookie: 'test' #Also tried this
else
render text: 'Wrong username and/or password', status: 401
end
end
end
路線:
Rails.application.routes.draw do
.
.
resources :sessions, :defaults => { :format => :json }
end
我遇到了同樣的問題。 以下是我的解決方法:
response.set_cookie "name", "nic"
我也想出了問題的原因。 偽造保護在響應組合之前使會話無效。
要使用cookies
方法,您需要跳過令牌的身份驗證:
skip_before_action :verify_authenticity_token
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.