Rails 4: set cookie in request / response if JSON type?

How to set a cookie when responding to a request like application / json in Rails?

The controller action works as expected, but the cookie is not set and there is no Set-Cookie header in the response. Any help would be greatly appreciated.

Controller:

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 

Route:

 Rails.application.routes.draw do . . resources :sessions, :defaults => { :format => :json } end 
+6
source share
1 answer

I am facing the same problem. Here is how I decided:

 response.set_cookie "name", "nic" 

I also came up with the cause of the problem. This is a fake protection that ends the session just before a response is generated.

To use cookies , you need to skip token authentication:

 skip_before_action :verify_authenticity_token 
+13
source

Source: https://habr.com/ru/post/982760/


All Articles