首页 > 解决方案 > 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('/');
});

标签: javascriptnode.jsexpress

解决方案


推荐阅读