javascript - Rails API 中的 ActionController::UnknownFormat 使用 JavaScript 前端获取请求

标签 javascript ruby-on-rails json

SPA html/JavaScript Rails 应用程序,带有 json API 后端,用于向前端提供数据。索引页面完全使用 javascript_pack_tag 中的 JS 显示和构建。然后我都调用自己的 api 来获取 PG 中保存的 json 数据,然后调用第三方 API openweathermap。一切都按照我想要的方式工作,然后我尝试使用 gon gem 存储我的 openweathermap API key 。我能够做到这一点。然而它破坏了我的应用程序。然后我解开了所有 gon gem 的东西,但应用程序仍然损坏。

错误
终端

#ubuntu terminal
ActionController::UnknownFormat (CitiesController#index is missing a template 
for this request format and variant.

request.formats: ["application/json"]
request.variant: []):   

控制台

#chrome console
class_mode.js:238 GET http://localhost:3000/cities.json 406 (Not Acceptable)
fetchCityData @ class_mode.js:238
(anonymous) @ class_mode.js:9
localhost/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 
#class_mode.js 
line 238> return fetch(BASE_URL).then(res => res.json()).then(function (json) { 

从这些错误中,我将其追溯到我的 Controller 操作返回 HTML 而不是 JSON。具体来说,< 表示 Controller 中返回的 html。

在 Controller 中修复的最新尝试

 def index 
   @all = City.all_in_json  
   respond_to do |format|
      format.html { render :index }
      format.json { @all }
    end
   end   

我还将 json 逻辑移至 City 模型中

def  self.all_in_json 
         @cities = self.all
              @returnValue = @cities.map do |city|  
             if city[:name] === nil 
                city[:name] = city.to_name 
                city.save! 
                city
             else
                city
              end  
              end  
            @returnValue.to_json 

    end 

这个应用程序再次完美运行。我现在已经花了一整天的时间进行调试,现在正在转向 StackOverflow。
我尝试创建不同的路由来调用我的 fetch() 请求,以检索 City 表/尝试的 respond_to 的所有记录。

最佳答案

您的 Controller 操作不会说明要渲染什么,它只是调用 @all 变量。假设您正确地将 @all 分配给 json 字符串,然后尝试更改您的 Controller 方法:

 def index 
   @all = City.all_in_json  
   respond_to do |format|
      format.html { render :index }
      format.json { render json: @all, status: 200, message: 'bla' }
   end
 end

状态和消息是可选的

关于javascript - Rails API 中的 ActionController::UnknownFormat 使用 JavaScript 前端获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61163368/

相关文章:

javascript - 再次单击同一选项卡时如何停止 react 中的无限循环

javascript - 存储配置数据 (json)

javascript - Nginx 在 POST .js 请求上返回 404

php - 为什么这个 JSON.parse 代码不起作用?

javascript - GBK 编码/解码字符集

javascript - 覆盖 Backbone.Wreqr.radio 处理程序

ruby-on-rails - 给定点和多边形的集合,确定哪个点位于(或不在)哪个多边形中

ruby-on-rails - sidekiq 在线程之间共享变量

json - 在redis中将结构存储为字符串

javascript - JSON 请求中既没有 Alert 也没有 Console.log 触发