如何解决在 DELETE 请求后完成 res.redirect(303, '/') 后页面未刷新
在 DELETE 请求后,我设法将页面重定向到主页 GET 路由,但该页面实际上并未刷新(即已删除的项目仍然出现),并且直到我手动刷新页面后,页面才真正刷新已移除。我已经做了一些console.logs,当它重定向到.get('/') 时,该项目肯定已被删除。任何想法为什么这不起作用?
app.js - 仅路由
app.route('/')
.get((req,res) => {
connection.query('SELECT * FROM todos',(err,results) => {
if (err) throw err;
console.log(results);
console.log('Todos read from database');
res.render('home',{ results: results });
});
})
.post((req,res) => {
const todoItem = req.body.todo;
connection.query('INSERT INTO todos (todo) VALUES (?)',todoItem,err => {
if (err) throw err;
console.log('Todo inserted into database.');
res.redirect('/');
});
})
.delete((req,res) => {
const todo = req.body.todoItem;
connection.query('DELETE FROM todos WHERE todo=?',todo,err => {
if (err) throw err;
console.log('Todo deleted from database.');
});
res.redirect(303,'/');
});
client.js
'use strict';
let todoItems = document.getElementsByClassName('todo-item');
for (let i = 0; i < todoItems.length; i++) {
todoItems[i].addEventListener('click',handleClick);
}
function handleClick(e) {
const todoTag = e.target.closest('.todo-item');
const todoItem = todoTag.getElementsByClassName('todo')[0].innerText;
const clicketodo = {
todoItem: todoItem
};
fetch('http://localhost:3000/',{
method: 'DELETE',body: JSON.stringify(clicketodo),headers: { 'Content-type': 'application/json; charset=UTF-8' }
})
.then(response => response.json())
.catch(err => console.log(err));
}
终端输出
Todo deleted from database.
[ RowDataPacket { todo: 'Clean' },RowDataPacket { todo: 'Read' } ]
Todos read from database
解决方法
我了解到,如果 fetch 获得重定向响应,它不会将浏览器发送到新页面,而这需要在客户端完成。我添加了 window.location = response.url 并且它现在可以工作了:
'use strict';
let todoItems = document.getElementsByClassName('todo-item');
for (let i = 0; i < todoItems.length; i++) {
todoItems[i].addEventListener('click',handleClick);
}
function handleClick(e) {
const todoTag = e.target.closest('.todo-item');
const todoItem = todoTag.getElementsByClassName('todo')[0].innerText;
const clickeTodo = {
todoItem: todoItem
};
fetch('http://localhost:3000/',{
method: 'DELETE',body: JSON.stringify(clickeTodo),headers: { 'Content-type': 'application/json; charset=UTF-8' }
})
.then(response => {
window.location = response.url;
response.json();
})
.catch(err => console.log(err));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。