javascript - Express res.redirect 不在帖子中重定向
问题描述
我对 res.redirect() 有一个小问题;
我编写了一个函数,在单击按钮时会向服务器发送一个发布请求并且它正在工作。但是当我尝试使用 res.redirect("/") 时,它会将我重定向到服务器上的主路由,但浏览器中没有任何反应。
这是代码:
发送 post 请求的函数。
const sendData = () =>{
const title = document.getElementById('titleOfArticle').value;
const textForPublish = document.getElementById('textForPublish').value;
const data = {
title,
textForPublish
}
const options = {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
}
fetch('/compose', options);
}
服务器代码:
const bodyParser = require("body-parser");
const ejs = require("ejs");
const posts = []; //array for all posts
const homeStartingContent = "text 1";
const aboutContent = "text 2";
const contactContent = "text 3";
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/", (req,res) => {
res.render('home', {homeContent: homeStartingContent});
console.log(posts);
})
app.get("/about", (req,res) => {
res.render('about', {aboutContent: aboutContent});
})
app.get("/contact", (req,res) => {
res.render('contact', {contactContent: contactContent});
})
app.get("/compose", (req,res) => {
res.render('compose');
})
app.post('/compose', (req,res) => {
const post = {
title: req.body.title,
content: req.body.textForPublish
};
posts.push(post);
res.redirect('/');
});
解决方案
推荐阅读
- keras - keras 在大数据集上单独训练
- tensorflow - tf.keras.backend 的 sum/avg/mean ops 在批处理轴上无法正常工作
- python - Bash 脚本 - 使用 Python 输出时找不到命令错误
- spring - 如何将日期时间放入正文 POSTMAN
- c - 函数调用参数的生命周期
- javascript - 使用自定义钩子反应检测组件外部的点击
- android - Android 谷歌登录警告
- database - 我应该更好地使用 VARCHAR(3) 或 BIGINT() 作为 PostgreSQL 的主键吗?
- r - 回归系数与效应大小相同吗?
- python - Pyinstaller Python 和 Matplotlib 版本在处理可执行文件 Windows 10 时导致 RuntimeError