【发布时间】:2018-01-27 18:04:50
【问题描述】:
在将这些拼图拼凑在一起时遇到一些问题...我正在抓取一个网站以获取一组字符串,我希望将数组发送回我的 React 客户端以供使用。这就是我所拥有的
index.js
componentDidMount() {
const { restaurant } = this.state
axios.post('/api/scraper', { restaurant: restaurant })
.then((res) => {
console.log(res.data);
})
}
app/controllers/api/scraper_controller.rb
class Api::ScraperController < ApplicationController
respond_to :json
def create
@info = helpers.get_info(params[:restaurant])
respond_with @info
end
end
app/helpers/api/scraper_helper.rb
module Api::ScraperHelper
def get_info(restaurant)
puts restaurant
require 'openssl'
doc = Nokogiri::HTML(open('http://www.subway.com/en-us/menunutrition/menu/all', :ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE))
@items = []
doc.css('.menu-cat-prod-title').each do |item|
@items.push(item.text)
end
end
end
整个想法是将 @items 数组发送回我的 React 页面上的 axios 请求
【问题讨论】:
-
您是否尝试将
@items添加为要返回的get_info方法的最后一行?或使用Array#map? -
@SebastianPalma 我尝试在我的
get_info函数中添加respond_with @items,但我收到了undefined method错误
标签: ruby-on-rails ruby ajax reactjs axios