Proper usage of Express' res.render() and res.redirect()

天涯浪子 提交于 2021-01-29 21:49:03

问题


I am using a res.redirect('page.ejs'); and on my browser I get the message:

Cannot GET /page.ejs

I have not declared this in my routes file in the style of :

app.get('/page', function(req, res) {
        res.render('page.ejs');
    });

Should this be included in order for the res.redirect() to work?

When I do not use res.redirect() but res.render(), even if I have not the app.get() code, it still works.


回答1:


so to understand this, let's look at what each of these methods do.

res.redirect('page.ejs');

this will tell express to redirect your request to the GET /page.ejs endpoint. An endpoint is the express method you described above:

app.get('/page', function(req, res) {
    res.render('page.ejs');
});

since you don't have that endpoint defined it will not work. If you do have it defined, it will execute the function, and the res.render('page.ejs') line will run, which will return the page.ejs file. You could return whatever you want though, it can be someOtherPage.ejs or you can even return json res.json({ message: 'hi' });


res.render('page.ejs');

this will just respond to the client (the front-end / js / whatever you want to call it) with the page.ejs template, it doesn't need to know whether the other endpoint is present or not, it's returning the page.ejs template itself.

so then, it's really up to you what you want to use depending on the scenario. Sometimes, one endpoint can't handle the request so it defers the request to another endpoint, which theoretically, knows how to handle the request. In that case redirect is used.

hope that makes sense and clarifies your confusion

(I'm not an expert on the inner-workings of express, but this is a high-level idea of what it's doing)




回答2:


You should do res.redirect('/page')



来源:https://stackoverflow.com/questions/52063162/proper-usage-of-express-res-render-and-res-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!