I have a small issue with res.redirect();
I've written a function that on button click sends a post request to the server and it's working. But when I try to use res.redirect("/"), it redirects me to home route on the server, but nothing happens in the browser.
Here is the code:
A function that sends post request.
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);
}
Server code:
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('/');
});