本文介绍了验证用户身份,使用XHR请求重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看以帮助我进行设置

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

在本指南中,作者仅允许用户在登录后添加到购物篮中(这也意味着按钮直到此时才可见),但是我不希望受到此限制,因此添加到购物车将始终可见,但是如果单击时未登录,则将重定向到登录名/ signup页面。

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.

在控制器内,我们使用的是 before_filter:authenticate_user!,默认情况下它将重定向回注册/登录后来自您的页面的页面(或者,我相信,如果这不正确,请告知。)

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).

我遇到的问题是通过XHR请求。这是到目前为止的设置

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

查看

<%=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

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)

当我单击添加到购物车时会发生什么,就是请求失败并显示控制台中 401未经授权,响应为您需要登录或注册后才能继续。

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.

我该怎么办?

推荐答案

您应该在ajax响应中捕获401然后像这样重定向:

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 = '/'

这篇关于验证用户身份,使用XHR请求重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 23:11