【问题标题】:Rails is parsing a request as html even though it's jsonRails 将请求解析为 html,即使它是 json
【发布时间】:2016-08-12 17:53:53
【问题描述】:

我正在尝试使用 Rails 创建一个 API。当我尝试在浏览器中使用 json 发出 ajax 请求时:

$.ajax({
  type: "GET",
  url: 'http://localhost:3000',
  dataType: "json",
  contentType: "application/json; charset=utf-8"
});

rails 服务器像 html 一样查看它,从日志中可以看出:

Started GET "/" for ::1 at 2016-08-12 13:52:00 -0400
  ActiveRecord::SchemaMigration Load (0.6ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by LandingsController#index as HTML

它应该说是 JSON,因为请求是 JSON。

【问题讨论】:

  • 我不是 100% 确定,但我认为 dataType 只告诉 jQuery 将响应解析为 JSON。它不会告诉服务器您正在请求 JSON。取自文档:“您期望从服务器返回的数据类型。”

标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4


【解决方案1】:

这取决于您的路由设置方式,而不仅仅是您在请求中传递的内容。您应该在routes.rb 中设置默认格式,如下所示:

root 'your_root_controller#index', format: 'json'

应该在 Rails 4 和 5 中工作。

【讨论】:

    猜你喜欢
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2021-12-26
    • 2010-12-31
    相关资源
    最近更新 更多