LoginSignup
0
1

More than 1 year has passed since last update.

Reactとの連携 6 YahooNewsを表示してみる

Posted at

以下に書き換えます。

app/controllers/data_controller.rb
class DataController < ApplicationController
  def index
  end

  def ajax
    url = 'https://news.yahoo.co.jp/pickup/rss.xml'#1 YahooNewのURL
    uri = URI.parse(url)
    response = Net::HTTP.get_response(uri)
    render plain:Hash::from_xml(response.body).to_json
  end
end

・Rubyの外部サーバーにアクセスする機能「Net::HTTP(アドレス)」クラス
・URI.parseを使うと、URLの文字列をURIオブジェクトへと生成いたします。

require 'uri'
uri = URI.parse("https://www.google.co.jp/")
p uri.scheme 
p uri.host 
p uri.port 
p uri.path
uri.scheme => "https"
uri.host => "www.google.co.jp"
uri.port => "443"
uri.path => "/"

実行するとこのようになります。これはhttpの構成要素を以下のように分解して出力しています。

・ Net::HTTPResponse
指定した対象に GET リクエストを送り、そのレスポンスを Net::HTTPResponse として返します。
対象の指定方法は URI で指定するか、 (host, path, port) で指定するかのいずれかです。

uri データの取得対象を URI で指定します。
host 接続先のホストを文字列で指定します。
path データの存在するパスを文字列で指定します。
port 接続するポートを整数で指定します。

lcalhost:3000/data/ajaxにアクセス

20210503-151541.png

取得できました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1