POST / Redirect / GET
Learning objectives
- Knows how to use the POST/Redirect/GET pattern in oak.
When working with vanilla Deno, we learned the basic concepts of the POST/Redirect/GET pattern and learned to incorporate that into our web applications. Here's a quick quiz to refresh your memory.
Question not found or loading of the question is still in progress.
Let us take a brief look into creating the POST/Redirect/GET pattern with the router. While previously, we have had to set the status code 303 and the 'Location' response header to the response, oak provides a ready-made method redirect
that does the work for us.
The redirect
method is a part of the response
object. The method takes the path to which the request should be redirected as a parameter -- no status code or header needs to be set. The following example, which is a modification of the previously seen counter, shows how the POST/Redirect/GET -pattern works when using oak.
import { Application, Router } from "https://deno.land/x/oak@v12.6.1/mod.ts";
const app = new Application();
const router = new Router();
let count = 0;
const getCount = ({ response }) => {
response.body = `${count}`;
};
const increaseCount = ({ response }) => {
count++;
response.redirect("/");
};
router.get("/", getCount)
.post("/", increaseCount);
app.use(router.routes());
app.listen({ port: 7777 });
When we try out the application, we observe that the server responds to POST requests with appropriate redirect headers. While we previously used the status code 303
, the server seems to use the status code 302
. This works as well.
curl http://localhost:7777
0%
curl -v -X POST http://localhost:7777
// ...
< HTTP/1.1 302 Found
< content-length: 17
< location: /
< content-type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
Redirecting to /.%
curl -v -X POST http://localhost:7777
// ...
< HTTP/1.1 302 Found
< content-length: 17
< location: /
< content-type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
Redirecting to /.%
curl http://localhost:7777
2%
When we study the responses to the requests we observe that, in addition to the correct headers, the server also responds with a textual message telling what is happening. The message Redirecting to /.
can be useful, for example, if the browser does not automatically follow redirect responses.