gpt4 book ai didi

ruby-on-rails - Rails 4 - 无需身份验证的 Json 渲染

转载 作者:数据小太阳 更新时间:2023-10-29 08:38:00 32 4
gpt4 key购买 nike

我是 RoR 的新手。到目前为止,在我的项目中,我使用 Devise gem 进行身份验证。所有的工作都很好。但我想在 index 上获取对 API 的 json 非授权访问。我为此做了一些尝试。

在我的应用程序 Controller 中。

class ApplicationCotroller < Action Controller::Base
protect_from_forgery_with :exception, :null_session => true
before_action :authenticate_user!, except: :index
end

这是我的产品 Controller 索引

class ProductsController < ApplicationController
skip_before_action :authenticate_user!, only: :index, if: -> { request.format.json? }
before_action :set_product, only: [:show, :edit, :update, :destroy]

def index
@products = Product.all
respond_to do |format|
format.html
format.json { render json: @products}
end
end

当我请求获取json

http://localhost:3000/products.json

它工作正常。即使这样也会加载 UI index 页面。

我只需要检查它是否是 JSON 请求。

如何实现?

最佳答案

试试这个:

class ProductsController < ApplicationController
skip_before_action :authenticate_user!, if: :skip_authenticate_user

def index
...
end

protected
def skip_authenticate_user
action_name=='index' && (request.format.json? || request.format.xml?)
end
end

关于ruby-on-rails - Rails 4 - 无需身份验证的 Json 渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23153979/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com