Authenticate user, redirect with XHR request

2019-09-08 03:58发布

问题:

I am looking at this guide to help me with setting up a "Add to Cart" feature within my application.

Within the guide the author only allows a user to add to the basket if they are signed in (which also means the button is not visible until this point), however I don't want to be restricted by this, so the "Add to Cart" would always be visible, but when clicking if you are not logged in then you would be redirected to the login/signup page.

Within the controller we are using the before_filter :authenticate_user! which by default will redirect back to the page you came from once you have signed up/signed in (or so I believe, please advise if this is incorrect).

The issue I have is achieving this with an XHR request. This is the setup so far

class CartsController < ApplicationController
  before_action :authenticate_user!
  def show
    cart_ids = $redis.smembers current_user_cart
    @cart_images = Image.find(cart_ids)
  end

  def add
    $redis.sadd current_user_cart, params[:image_id]
    render json: current_user.cart_count, status: 200
  end

  def remove
    $redis.srem current_user_cart, params[:image_id]
    render json: current_user.cart_count, status: 200
  end

  private

  def current_user_cart
    "cart#{current_user.id}"
  end
end

View

<%=link_to "", data: { target: @cart_action, addUrl: add_to_cart_path(@image), removeUrl: remove_from_cart_path(@image) } do %>
  <i class="di-shopping-cart-up"></i>
  <span><%= @cart_action %></span> Cart
<% end %>

CoffeeScript

$(window).load ->
  $('a[data-target]').click (e) ->
    e.preventDefault()
    $this = $(this)
    if $this.data('target') == 'Add to'
      url = $this.data('addurl')
      new_target = "Remove from"
   else
    url = $this.data('removeurl')
    new_target = "Add to"
  $.ajax url: url, type: 'put', success: (data) ->
  $('.badge-number').html(data)
  $this.find('span').html(new_target)
  $this.data('target', new_target)

What happens at the moment when I click "Add to Cart" is that the request fails with a 401 Unauthorized in the console with the response You need to sign in or sign up before continuing.

How can I approach this?

回答1:

You should catch the 401 in your ajax response and then redirect like this:

  $(document).on "ajaxError", (event, request, settings) ->
    if request.status == 401
      window.location.href = '/'