【问题标题】:JSON::ParserError in CoursesController#indexCoursesController#index 中的 JSON::ParserError
【发布时间】:2018-01-28 09:58:44
【问题描述】:

我是 Ruby on Rails 和 Web 开发的初学者。我正在参加在线课程,但讲座示例一直失败。

我的问题是我的课程控制器,索引操作。

控制器:my_first_app/controllers/courses_controller.rb

class CoursesController < ApplicationController
  def index
    @search_term = 'jhu'
    @courses = Coursera.for(@search_term)
  end
end

型号:my_first_app/models/coursera.rb

class Coursera
  include HTTParty

  #default_options.update(verify: false) # Turn off SSL verification
  base_uri 'https://api.coursera.org/api/catalog.v1/courses'
  default_params fields: "smallIcon,shortDescription", q: "search"
  format :json

  def self.for term
    get("", query: { query: term})["elements"]
  end
end

查看:my_first_app/views/index.html.erb

<h1>Search for - <%= @search_term %> </h1>
<table border = "1">
    <tr>
        <th>Image</th>
        <th>Name</th>
        <th>Description</th>
    </tr>

<%= @courses.each do |course| %>
    <tr>
        <td><%= image_tag(course["smallIcon"]) %></td>
        <td><%= course["name"] %></td>
        <td><%= course["shortDescription"] %> </td>
    </tr>
<% end %>   

路由:my_first_app/config/routes.rb

Rails.application.routes.draw do
  get 'courses/index'
  get 'greeter/hello'
  get 'greeter/goodbye'
end

宝石文件:

source 'https://rubygems.org'
gem 'rails', '4.2.3'
gem 'sqlite3'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc

group :development, :test do
gem 'byebug'
gem 'web-console', '~> 2.0'
gem 'spring'
gem 'httparty', '0.13.5'
end

我将最后一个 gem 添加到 Gemfile 并运行包,然后我控制 +c 停止并重新启动服务器,我收到错误消息:

JSON::ParserError in CoursesController#index

error message screenshot

我认为这是说我解析的是 HTML 而不是 JSON,但我不知道如何修复它。任何帮助将不胜感激。 原始仓库:https://github.com/jhu-ep-coursera/fullstack-course1-module3

【问题讨论】:

    标签: html css ruby-on-rails json ruby


    【解决方案1】:

    根据 Coursera 的 API documentation,您的 base_uri 可能需要:

    base_uri 'https://api.coursera.org/api/courses.v1'
    

    然后对于default_params 中的fields 应该(可能)是:

    default_params fields: "photoUrl,description", q: "search"
    

    (在您的应用中也将其他出现的'smallIcon''shortDescription' 更改为'photoUrl''description',因为我在api 文档中看不到这些字段)。

    一旦进行了这些更改,您最终应该会访问像 https://api.coursera.org/api/courses.v1?q=search&query=ruby&fields=photoUrl,description 这样返回有效 JSON 的 URL。您当前使用的base_uri 会将您发送到一个HTML 错误页面,告诉您找不到操作。因为那是一个 HTML 页面,所以 JSON 无法解析它。

    如果您查看您链接的 Github 存储库中最后一次提交的日期,最后一次提交是在 2015 年 11 月,大约是 2 年前。只是超级过时了,从那时起 API 可能已经发生了相当大的变化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      相关资源
      最近更新 更多