Rails API: 使应用程序控制器服务 JSON

Rails API: make application controller serve JSON

This tutorialReact + Flux 由 Rails API 支持,Fancy Pixel 说:

Now we need to change the application controller so that it inherits from ActionController::API, and kiss the protect_from_forgery goodbye. Since we are serving only JSON, it makes sense to add

respond_to :json

to the applciation controller, helps DRYing all out. While we are at it, we might as well delete the assets and views folders, we won’t need them.

我不确定我应该做什么。

这是我的应用程序控制器的样子:

class ApplicationController < ActionController::API
    respond_to :json
end

是否正确?

此外,我应该保留还是删除 protect_from_forgery with: :null_session :

class ApplicationController < ActionController::API
  protect_from_forgery with: :null_session
  respond_to :json
end

要从任何 Rails 后端(甚至不一定只是 API)进行通信,您所要做的就是在 API 的控制器中写入以下内容:

class Api::V1::SearchController < ApplicationController
#Run an Authentication Method on their API Key
before_action :authenticate

  def search
    #Performs your backend logic
    content_array = get_content_method
    render :json => content_array
    #Renders up a JSON that you can retrieve with an HTTP get request
  end
end

关于提供数据的主题,您可以在一个模糊的 JSON 中发送您的参数,允许您隐藏您的 API 密钥,从而保护您免受不必要的访问。我最喜欢的方法是使用 .to_query 方法发送必要的参数。我是这样做的:

BASE_URL = "http://yourwebsite.com/search?"

def generate_search_url(params)
    BASE_URL + params.to_query + "&Api-Key=#{ENV['API-KEY']}"
end

通过这种方式,您可以像处理任何其他参数一样处理给定的数据,但如果没有授予的密钥,滥用 API 会更加困难。