我一直在努力解決這個問題。這是我的 JS 類:
class Comment {
constructor(comment) {
this.id = comment.id
this.comment = comment
}
static createComment(e){
e.preventDefault()
const commentMessage = e.target.children[0].value
const commentList = e.target.previousElementSibling
Comment.submitComment(commentMessage, commentList)
e.target.reset()
}
renderComment(commentList){
const p = document.createElement('p')
p.dataset.id = this.id
p.innerText = "- " this.comment " "
}
static submitComment(commentMessage, commentList){
fetch(commentsURL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
body: JSON.stringify({
comment: commentMessage
}),
})
.then(response => response.json())
.then(comment => {
let newComment = new Comment(comment)
newComment.renderComment(commentList)
})
}
}```
從我的 Rails API 回傳以下錯誤:
“NoMethodError(“評論”的未定義方法“許可”:字串):
app/controllers/comments_controller.rb:24:in comment_params' app/controllers/comments_controller.rb:8:in create'"
這是控制器:
class CommentsController < ApplicationController
def index
comments = Comment.all
render json: comments
end
def create
comment = Comment.new(comment_params)
if comment.save
render json: comment
else
render json: {errors: comment.errors.full_messages}
end
end
private
def comment_params
params.require(:comment).permit(:comment)
end
end
歡迎提供任何幫助,我會根據需要盡量保持清晰。
uj5u.com熱心網友回復:
看起來 ruby?? 控制器正試圖對回傳字串執行一個操作,這不是一個有效的方法。你.permit()從哪里得到的?也許在 ruby?? 論壇中提問?
它回傳 [Object object] 的原因是因為您期望在 fetch 請求中包含一個 json 物件。您通常只會呈現從 json 物件中的值之一回傳的字串,但在這種情況下,它是一個錯誤物件。
uj5u.com熱心網友回復:
你用這個發表你的評論:
fetch(commentsURL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
body: JSON.stringify({
comment: commentMessage
}),
})
這意味著您將像{ "comment": "Comment text goes here..." }Rails一樣發送 JSON 。
然后在 Rails 中,你嘗試用這個解壓它:
params.require(:comment).permit(:comment)
這就是說“引數必須具有comment欄位并在該comment欄位中查找該comment欄位”。所以它正在尋找這樣的 JSON:
{
"comment": {
"comment": "Comment text goes here.."
}
}
因此,更改您的 JSON 以匹配您的引數決議:
JSON.stringify({
comment: { comment: commentMessage }
})
或更改您的引數決議以匹配您的 JSON:
params.permit(:comment)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/380432.html
標籤:javascript 红宝石轨道 接口 类型
