Enonic version: 6.5.2
OS: Windows 7
Is there is any way to make redirect from part that consuming “GET” request(if it get wrong initial data, for example).
Is there is any way to make redirect from part that consuming “GET” request(if it get wrong initial data, for example).
I think it could be done by throwing exception from part, with some data(redirect url), than catch it in error interceptor and redirect from it. But it’s not really an elegant way.
Yes, you can redirect to another page. Take a look at the response object http://xp.readthedocs.io/en/stable/developer/ssjs/http-response.html
Simply check for the “wrong initial data” and then return the response with a redirect
instead of a body
.
Instead of this:
return {
body: thymeleaf.render(view, model)
};
Use this:
return {
redirect: otherPage
};
I have a situation that was mentioned here: Throw 404 from a part
If I will return redirect from part(not page) it will not do anything, and just render “emty” part since I haven’t send body in response.
Hi!
Redir from a part is conceptually bad, is there a reason why you cannot handle this in the page controller?
There are many scenarios that might fail bad - there is a good reason why a part cannot change the response content type of a whole page for instance.
The thing that I will know about false condition only inside of part, and if part will not be able to show anything, then there is no reason to show page at all…
Than the only possible solution for me is to throw exception from part with Json data, and handle it inside error handler, and redirect from there.
Oh, I see. Well then maybe just return some javascript in the part that will redirect the user to the desired page.
window.location = “http://www.example.com”;
yes, I also was thinking about such possibility, but it’s better to do such things on server side, cause client side code always can be changed by someone.
Still not sure why this check cannot be in the page controller, just make a checkbox/setting for this in the page?
I have a <form>
in a part that needs to return a redirect (status 303) on success to move to the next <form>
in a series.
The way I hacked it solved it, was to return the url I wanted to redirect to as part of the header:
return {
header: {
"x-redirect": myUrlToRedirectTo
}
}
And use a response processor to change the response:
export function responseProcessor(req, res) {
const redirectUrl = res.headers?.["x-redirect"];
return (redirectUrl !== undefined)
? {
...res,
status: 303,
redirect: redirectUrl
}
: res;
}
This technique can of course also be used to let a part decide which http status code to use. Just add the wanted status code in header, and parse in the filter like above.
Maybe serve up a nice 400
if a form has errors.
Now smash that -button if this helped you!