发送来自助手的 JSON 响应到 Rails 中的#create
Send JSON response from helper to #create in Rails
在将这些拼图组合在一起时遇到一些问题...我正在抓取一个网站以获取字符串数组,我希望将该数组发送回我的 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
请求
您的实际代码将只是 return 0,因为在这种情况下,在 Nokogiri::XML::NodeSet
中应用 each
的结果是 0,这就是您要留下的最后一个在你的方法中执行 "piece of code",所以 Ruby 将 return this.
如果你在最后一行添加@items,那么这将是returned,你会得到["Black Forest Ham", "Chicken & Bacon Ranch Melt", ...]
,我想这就是你需要的:
@items = []
doc.css('.menu-cat-prod-title').each { |item| @items.push(item.text) }
@items
请注意,您还可以对 doc.css('.menu-cat-prod-title')
执行映射操作,然后可以将其分配给任何实例变量:
def get_info(restaurant)
...
doc.css('.menu-cat-prod-title').map(&:text)
end
我想 return 您可以使用类似 render json: { items: @items }
的创建数据,因为项目包含菜单数组。
在将这些拼图组合在一起时遇到一些问题...我正在抓取一个网站以获取字符串数组,我希望将该数组发送回我的 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
请求
您的实际代码将只是 return 0,因为在这种情况下,在 Nokogiri::XML::NodeSet
中应用 each
的结果是 0,这就是您要留下的最后一个在你的方法中执行 "piece of code",所以 Ruby 将 return this.
如果你在最后一行添加@items,那么这将是returned,你会得到["Black Forest Ham", "Chicken & Bacon Ranch Melt", ...]
,我想这就是你需要的:
@items = []
doc.css('.menu-cat-prod-title').each { |item| @items.push(item.text) }
@items
请注意,您还可以对 doc.css('.menu-cat-prod-title')
执行映射操作,然后可以将其分配给任何实例变量:
def get_info(restaurant)
...
doc.css('.menu-cat-prod-title').map(&:text)
end
我想 return 您可以使用类似 render json: { items: @items }
的创建数据,因为项目包含菜单数组。