我正在尝试使用 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。
最佳答案
这取决于您的路由设置方式,而不仅仅是您在请求中传递的内容。您应该在 routes.rb
中设置默认格式,如下所示:
root 'your_root_controller#index', format: 'json'
应该适用于 Rails 4 和 5。
关于javascript - Rails 将请求解析为 html,即使它是 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38923853/