【发布时间】:2021-07-30 19:26:13
【问题描述】:
我有一个应用在后端运行 Rails,Javascript 前端。我的控制器、路由和 CORS 都很好。我的 Post 和 Get 请求运行良好。但是,当我提出补丁请求时,它成功地进行了补丁,但是作为response.text(),我得到了空字符串。所以当我使用response.json() 时,它给了我Uncaught (in promise) SyntaxError: Unexpected end of JSON input at game.js:25 error. 我需要知道问题的根源。
static patchGame() {
const numberOfClicks = parseInt(document.getElementById('click-number').textContent, 10)
const score = parseInt(document.getElementById('score').textContent,10)
const gameID = document.getElementById('gameID').value
const gameObj = {game: {click_number: numberOfClicks, score: score}}
const options = {
method: "PATCH",
headers: {"Content-Type": "application/json",
"Accept": "application/json"},
body: JSON.stringify(gameObj)
}
fetch(`http://localhost:3000/games/${gameID}`, options).then(resp => {debugger}).then(game => { debugger }) // NEVER HITS last debugger
}
这些是我得到的 resp 调试器值,
>resp
<-Response {type: "cors", url: "http://localhost:3000/games/28", redirected: false, status: 204, ok: true, …}
body: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 204
statusText: "No Content"
type: "cors"
url: "http://localhost:3000/games/28"
__proto__: Response
>resp.text()
<-Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined
>resp.json()
<-Promise {<rejected>: TypeError: Failed to execute 'json' on 'Response': body stream already read
at eval (eval at <a…}
__proto__: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: TypeError: Failed to execute 'json' on 'Response': body stream already read at eval (eval at <anonymous> (file:///Users/muratogulcansahin/Desktop/DanceMemory/frontend/game.js:1:1), <anonymous>:1:6) at file:///Users/muratogulcansahin/Desktop/DanceMemory/frontend/game.js:24:84
message: "Failed to execute 'json' on 'Response': body stream already read"
stack: "TypeError: Failed to execute 'json' on 'Response': body stream already read\n at eval (eval at <anonymous> (file:///Users/muratogulcansahin/Desktop/DanceMemory/frontend/game.js:1:1), <anonymous>:1:6)\n at file:///Users/muratogulcansahin/Desktop/DanceMemory/frontend/game.js:24:84"
__proto__: Error
>resp.body
<-ReadableStream {locked: true}
locked: true
__proto__: ReadableStream
【问题讨论】:
-
你能显示响应正文是什么吗?
-
尝试将响应对象打印到控制台以查看我们正在处理的内容。
.then(resp => console.log(resp) -
嘿——你能显示这条路线的相应控制器动作吗?(以及与返回你可能在关注点或库中可能有的数据对象相关的任何逻辑)
-
@Joel_Blum,我用更多信息更新了这个问题。谢谢你们的帮助。
标签: javascript ruby-on-rails ajax api patch