当我通过 Go REST API 在管理页面中的数据库中搜索报价时,报价显示正常,并且可以填充其文本、作者和类别的编辑字段。然而,问题是,一旦我进行更改并单击“更新”按钮,数据库中的报价实际上并没有更新。在这个问题的末尾,我输入了我认为的来源问题,我希望能帮助解决该问题。
当前的行为是,假设我要更改以下引用中的这个拼写错误,以将“我们挑战改变自己”更正为“我们挑战d改变自己”,按下更新按钮没有错误,但是当我再次搜索相同的报价时,没有应用更新。
请注意,所有这些函数都包含在我的
<script>
文件中的 admin.html.tmpl
HTML 标记中:
function searchQuotes() {
const keyword = document.getElementById('searchInput').value;
fetch(`/admin/search/${keyword}`)
.then(response => response.json())
.then(quotes => {
const searchResultsDiv = document.getElementById('searchResults');
searchResultsDiv.innerHTML = ''; // Clear previous search results
quotes.forEach(q => {
// Create HTML elements to display each quote
const quoteDiv = document.createElement('div');
quoteDiv.className = 'quote'; // Add class name for styling
quoteDiv.dataset.id = q.ID; // Set dataset ID
quoteDiv.innerHTML = `
<input type="text" id="edit_text_${q.ID}" value="${q.text}" />
<input type="text" id="edit_author_${q.ID}" value="${q.author}" />
<input type="text" id="edit_classification_${q.ID}" value="${q.classification}" />
<p>Likes: ${q.likes}</p> <!-- Display the likes count -->
<button onclick="updateQuote('${q.ID}')" class="update">Update</button>
<span id="update_status_${q.ID}"></span>
`;
searchResultsDiv.appendChild(quoteDiv);
});
})
.catch(error => {
console.error('Error searching quotes:', error);
});
}
function editQuote(id) {
// Populate input fields with current quote information
const text = document.getElementById('edit_text_' + id).value;
const author = document.getElementById('edit_author_' + id).value;
const classification = document.getElementById('edit_classification_' + id).value;
// Set the current quote information to input fields
document.getElementById('edit_text_' + id).value = text;
document.getElementById('edit_author_' + id).value = author;
document.getElementById('edit_classification_' + id).value = classification;
}
function updateQuote(id) {
// Get the edited values
const editText = document.getElementById('edit_text_' + id).value;
const editAuthor = document.getElementById('edit_author_' + id).value;
const editClassification = document.getElementById('edit_classification_' + id).value;
fetch('/admin/edit/' + id, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
edit_text: editText, // <-- Use 'edit_text' instead of 'text'
edit_author: editAuthor, // <-- Use 'edit_author' instead of 'author'
edit_classification: editClassification // <-- Use 'edit_classification' instead of 'classification'
})
})
.then(response => {
if (response.ok) {
// Update UI to signify successful update
document.getElementById('update_status_' + id).innerText = '✔ Quote updated';
} else {
console.error('Failed to update quote');
}
})
.catch(error => {
console.error('Error updating quote:', error);
});
}
现在,以下是此功能对应的 Go REST API 路由:
// POST /admin/edit/:id - Edit a quote
r.POST("/admin/edit/:id", func(c *gin.Context) {
idStr := c.Param("id")
id, err := strconv.Atoi(idStr)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"message": "Invalid quote ID."})
return
}
// Parse the request body into a new quote struct
var editedQuote quote
if err := c.ShouldBindJSON(&editedQuote); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"message": "Invalid request body."})
return
}
// Check if the edited quote text already exists in the database
var existingID int
err = db.QueryRow("SELECT id FROM quotes WHERE text = $1 AND id != $2", editedQuote.EditText, id).Scan(&existingID)
if err == nil {
// Edited quote text already exists, return an error
c.AbortWithStatusJSON(http.StatusConflict, gin.H{"message": "Edited quote text already exists in the database."})
return
} else if err != sql.ErrNoRows {
log.Println(err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Failed to check if edited quote already exists in the database."})
return
}
// Update the quote in the database with the edited values
_, err = db.Exec("UPDATE quotes SET text = $1, author = $2, classification = $3 WHERE id = $4",
editedQuote.EditText, editedQuote.EditAuthor, editedQuote.EditClassification, id)
if err != nil {
log.Println(err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Failed to update the quote."})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Quote updated successfully."})
})
这是我从我的 API 托管服务(Railway)单击更新时的日志:
如您所见,API 路由没有正确的引用 ID 肯定存在问题,因为它调用了这个未定义的路由:
看来我只是在这里混淆了大小写,我试图访问
q.ID
,而它应该是q.id
。因此,我只是在代码的几个地方进行了更改来解决我的问题。
感谢 @Brits 通过建议生成的 HTML 中的打印语句来帮助我进行调试:
<p>ID: ${q.ID}</p> <!-- Display the ID -->
<p>ID: ${q.id}</p> <!-- Display the ID -->
这就是导致意识到大写错误的原因,因为后者打印了正确的 id 值。