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.
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
EJS templates need to be rendered, the client won't do that. Just use
res.render
, don't useres.redirect
at all here – Luca Kiebel Commented Aug 28, 2018 at 17:12 - If i use res.render() should i use the app.get() code? – user1584421 Commented Aug 28, 2018 at 17:12
-
If you want the user to see the rendered
page.ejs
when they visit/page
, useapp.get('/page', function(req, res) { res.render('page.ejs'); });
– Luca Kiebel Commented Aug 28, 2018 at 17:13
2 Answers
Reset to default 6so to understand this, let's look at what each of these methods do.
res.redirect('page.ejs');
// or, more correctly, you're redirecting to an *endpoint*
// (not a page. the endpoint will render a *page*) so it should be:
res.redirect('/page');
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)
You should do res.redirect('/page')
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744271460a4566120.html
评论列表(0条)