Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 using basic fetches and thunk

时间:2021-06-21 09:11:47

标签: javascript ruby-on-rails json redux fetch

我已经在我的 index.js 文件中正确导入并安装了 thunk。我正在尝试设置一个操作,该操作将在执行提取时呈现加载页面,然后在 .then() 块内进行第二次提取。这是因为每次 fetch 都需要从 rails 显示页面检索数据,然后使用该代码创建一个 JS 对象并将其添加到数组中。代码如下...

return (dispatch) => {
        dispatch({type: 'LOAD_FIGURE'})
        let movesLen = moves.length // Going to be either 2 or 3
        if (movesLen == 2){
            fetch(`http://localhost:3000/moves/show/${moves[0]}`)   // Generate first move
                .then(resp => resp.json())  
                .then(json => console.log(json))    // make this functional later
                .then(fetch(`http://localhost:3000/moves/show/${moves[1]}`)  // Generate the second move
                    .then(resp => resp.json())
                    .then(json => console.log(json)) // make this functional later
                )
        }
    }

这只会返回以下错误

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

我不确定这里会出现什么问题,因为此提取非常基本。我担心它与嵌套提取有关,但我收到两次错误的事实也让我想到,当它同时提取两者时,两者都返回相同的错误。

1 个答案:

答案 0 :(得分:0)

您需要告诉服务器(大概是您的 Rails 应用程序)您需要 JSON 响应。 Rails 将默认为 text/html,除非您另行指定或在路由中添加默认值。

这可以通过设置 the Content-Type header:

fetch(`http://localhost:3000/moves/show/${moves[0]}`, {
  headers: {
    'Content-Type': 'application/json'
  }
})

或者通过向 URL 添加扩展名:

fetch(`http://localhost:3000/moves/show/${moves[0]}.json`) ...

这会覆盖 Rails 中的头文件。当然,您还必须确保您的 Rails 应用实际上也使用有效的 JSON 响应请求。