将JSON从索引操作服务到公用文件夹中的index.html

Serve JSON from index action to index.html in public folder

本文关键字:文件夹 html index JSON 索引 操作 服务      更新时间:2023-11-30

我正试图使用Rails作为后端创建一个单页应用程序,因为这是我所知道的唯一的后端框架。我把所有文件都放在公用文件夹中,还安装了npm和jspm,这样我就可以使用javascript功能了。

我想做的是在我的电影控制器中进行索引操作

  def index
    @movies = Movie.all
    render :json => @movies
  end

将电影集合作为JSON数据发送到位于公用文件夹中的index.html文件。我正在使用"fetch"函数来检索client.js文件中的数据:

let api_url = 'http://127.0.0.1:3000'
fetch(api_url).then(function(resp) {
  resp.json().then(function(movies) {
    console.log(movies)
  })
})

这会导致以下错误:

Uncaught (in promise) SyntaxError: Unexpected token <

我不知道这意味着什么,也不知道我是否正确地处理了这件事。如有任何帮助,我们将不胜感激。

将其更改为:

let api_url = 'http://127.0.0.1:3000/movies'

两者相同:

fetch(api_url).then(function(resp) {
  resp.json().then(function(movies) {
    console.log(movies)
  })
})

fetch(api_url).then(r => r.json())
  .then(data => console.log(data))
  .catch(e => console.log('error'))