首页 > 解决方案 > ruby on rails 调用外部 api 并显示结果

问题描述

我正在尝试调用 API(喜欢https://jsonplaceholder.typicode.com/)。这个想法很简单,单击按钮以显示 res,但我在实现它时遇到了麻烦。我下面的只是调用该函数的按钮,并希望在控制台中打印它。

错误:

enter code here No route matches [POST] "/dashboard/fetch_action"

路线

resources :dashboard do
 collection do
   get :fetch_action
 end
end

仪表板控制器.er

require 'faraday'

def index
end

def fetch_action
    response = Faraday.get 'https://jsonplaceholder.typicode.com/posts/1'
    puts response
    # return response 
end

index.html.erb

    <%= button_to "fetch action", fetch_action_dashboard_index_path, class: "btn btn-warning" %>

谢谢

编辑:

路线:

Rails.application.routes.draw do

  devise_for :users
  
  devise_scope :user do
    root to: 'devise/sessions#new'
  end

  get 'dashboard' => 'dashboard#index'
  get '/dashboard/fetch-action', to: 'dashboard#fetch_action', as: 'dashboard_fetch_action'
  get '/user' => 'dashboard#index', :as => :user_root

end

耙路线

    new_user_session GET    /users/sign_in(.:format)                                                                 devise/sessions#new
             user_session POST   /users/sign_in(.:format)                                                                 devise/sessions#create
     destroy_user_session DELETE /users/sign_out(.:format)                                                                devise/sessions#destroy
        new_user_password GET    /users/password/new(.:format)                                                            devise/passwords#new
       edit_user_password GET    /users/password/edit(.:format)                                                           devise/passwords#edit
            user_password PATCH  /users/password(.:format)                                                                devise/passwords#update
                          PUT    /users/password(.:format)                                                                devise/passwords#update
                          POST   /users/password(.:format)                                                                devise/passwords#create
 cancel_user_registration GET    /users/cancel(.:format)                                                                  devise/registrations#cancel
    new_user_registration GET    /users/sign_up(.:format)                                                                 devise/registrations#new
   edit_user_registration GET    /users/edit(.:format)                                                                    devise/registrations#edit
        user_registration PATCH  /users(.:format)                                                                         devise/registrations#update
                          PUT    /users(.:format)                                                                         devise/registrations#update
                          DELETE /users(.:format)                                                                         devise/registrations#destroy
                          POST   /users(.:format)                                                                         devise/registrations#create
                     root GET    /                                                                                        devise/sessions#new
                dashboard GET    /dashboard(.:format)                                                                     dashboard#index
   dashboard_fetch_action GET    /dashboard/fetch-action(.:format)                                                        dashboard#fetch_action
                user_root GET    /user(.:format)                                                                          dashboard#index
       rails_service_blob GET    /rails/active_storage/blobs/:signed_id/*filename(.:format)                               active_storage/blobs#show
rails_blob_representation GET    /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
       rails_disk_service GET    /rails/active_storage/disk/:encoded_key/*filename(.:format)                              active_storage/disk#show
update_rails_disk_service PUT    /rails/active_storage/disk/:encoded_token(.:format)                                      active_storage/disk#update
     rails_direct_uploads POST   /rails/active_storage/direct_uploads(.:format)                                           active_storage/direct_uploads#create
           
                                                                                     

索引.html.eb

<%= link_to "fetch action", dashboard_fetch_action_path, class: "btn btn-info" %>

<%= @response %>

fetch-action.html.erb

<%= @response %>

仪表板控制器

def index
end

def show
end

def fetch_action
    uri = URI('https://jsonplaceholder.typicode.com/posts/1')
    req = Net::HTTP.get(uri)
    @response = JSON.parse(req)
end

错误(单击 link_to 重定向到仪表板/获取操作时出现以下错误):

DashboardController#show is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: [] NOTE! For XHR/Ajax or API requests, this action would normally respond with 204 No Content: an empty white screen. Since you're loading it in a web browser, we assume that you expected to actually render a template, not nothing, so we're showing an error to be extra-clear. If you expect 204 No Content, carry on. That's what you'll get from an XHR or API request. Give it a shot.

标签: ruby-on-railsrubyapimodel-view-controllerjsonplaceholder

解决方案


故障排除和设置路线

首先,在您的终端中,运行rake routes以打印出您的应用程序中的路线。在此处发布该输出。但是您需要检查fetch_action_dashboard_index_path您在按钮中使用的命令的输出 - 这是正确的路径吗?

我认为不是。还有一种更简单的方法来声明一条路线。您对路由中的资源声明所做的是为仪表板控制器的索引、显示、创建、更新和删除操作配置路由。您的 routes.rb 文件中的以下行将仅设置 fetch_action 路由并将其命名为“dashboard_fetch_action”</p>

get '/dashboard/fetch-action', to: 'dashboard#fetch_action', as: 'dashboard_fetch_action'

创建指向该路线的链接

第二; 使用link_to而不是 button_to 来确保您发出 GET 请求。您正在应用的 btn 类无论如何都会将该链接样式设置为看起来像一个按钮,并且a标签在语义上比button(因为您想要 GET)更正确,因此请使用:

<%= link_to "fetch action", dashboard_fetch_action_path, class: "btn btn-warning" %>

渲染动作的结果

最后确保您有一个文件,app/views/dashboard/fetch_action.html.erb其中会将 API 响应呈现为 HTML。此内容(或类似内容)将实现这一目标。

<%= @response =>

并且,在仪表板控制器中的 fetch_action 操作中。而不是response = Faraday...,使用@response = Faraday.... 这样response可以在视图 HTML 中访问对象(这就是 @ 表示的)

def fetch_action
    @response = Faraday.get 'https://jsonplaceholder.typicode.com/posts/1'
end

推荐阅读