I've seen the same question posted, but not many helpful answers. I would like to render the welcome page once I've done content of the app.post, but nothing happens.
I know it's valid as it will give me an error if i enter an invalid route, but it just will not do what i would like.
app.get('/', function (req, res) {
res.render('Welcome')
})
app.post('/makepost', function (req, res) {
//do some things
res.render('Welcome');
})
In the View I use this to call the app.post.
fetch('/makepost', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: body,
}
CodePudding user response:
When you make an Ajax call using fetch()
from your Javascript in the browser, the result from that ajax call just comes back to your Javascript. The browser does not automatically render or display anything.
So, if you want the displayed content to change, you have to either change window.location
to tell the browser to go to a new web page or you have to take the result from the fetch()
operation and insert it into the currently displayed page somehow.
A POST will only display automatically in the browser if it comes from a browser-sent form post where the browser sends the form POST to your server, not your Javascript. In that one case, it will take the result from the form POST and display it.
See How to properly redirect in NodeJS/ExpressJS? for some further explanation.
Note: You can, from your Javascript, call form.submit() or form.requestSubmit() where form
is the DOM object for your form and these will work similarly to the end-user pressing a submit button and the browser will display whatever response the server sends back after processing the form POST.
CodePudding user response:
If you simply want to redirect the user to homepage after the post, then you can do it:
app.post('/makepost', function (req, res) {
//do some things
res.redirect('/');
})
if you want to learn more about the render and view engines, please, take a look at the documentation of express: https://expressjs.com/pt-br/guide/using-template-engines.html
and this post at geekforgeeks.com: https://www.geeksforgeeks.org/express-js-res-render-function/
a brief for you, you should install a view engine like ejs, create a folder called views and put your pages into this folder and render it with the same name that you chose. I recommend that you use the express-generator to automate this task: https://expressjs.com/pt-br/starter/generator.html
another tip is to render your pages only in get methods, as the goal of post method is to send data to server and not fetch data or pages. Hope i helped you!