1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-11 16:42:21 -05:00

Fix http README examples (denoland/deno_std#440)

Some cosmetic fixes to the provided examples in the http README:
- Ensure they're all actually runnable
- Use clear variable names
- Add usage of Cookie interface
Original: b9b25b8b17
This commit is contained in:
Stoyan Dimkov 2019-05-23 19:05:00 +03:00 committed by Ryan Dahl
parent 632fbd7734
commit 73f7be6ae0

View file

@ -7,36 +7,46 @@ A framework for creating HTTP/HTTPS server.
Helper to manipulate `Cookie` throught `ServerRequest` and `Response`. Helper to manipulate `Cookie` throught `ServerRequest` and `Response`.
```ts ```ts
import { ServerRequest } from "https://deno.land/std/http/server.ts";
import { getCookies } from "https://deno.land/std/http/cookie.ts"; import { getCookies } from "https://deno.land/std/http/cookie.ts";
let req = new ServerRequest(); let request = new ServerRequest();
req.headers = new Headers(); request.headers = new Headers();
req.headers.set("Cookie", "full=of; tasty=chocolate"); request.headers.set("Cookie", "full=of; tasty=chocolate");
const c = getCookies(request); const cookies = getCookies(request);
// c = { full: "of", tasty: "chocolate" } console.log("cookies:", cookies);
// cookies: { full: "of", tasty: "chocolate" }
``` ```
To set a `Cookie` you can add `CookieOptions` to properly set your `Cookie` To set a `Cookie` you can add `CookieOptions` to properly set your `Cookie`
```ts ```ts
import { setCookie } from "https://deno.land/std/http/cookie.ts"; import { Response } from "https://deno.land/std/http/server.ts";
import { Cookie, setCookie } from "https://deno.land/std/http/cookie.ts";
let res: Response = {}; let response: Response = {};
res.headers = new Headers(); const cookie: Cookie = { name: "Space", value: "Cat" };
setCookie(res, { name: "Space", value: "Cat" }); setCookie(response, cookie);
const cookieHeader = response.headers.get("set-cookie");
console.log("Set-Cookie:", cookieHeader);
// Set-Cookie: Space=Cat
``` ```
Deleting a `Cookie` will set its expiration date before now. Deleting a `Cookie` will set its expiration date before now.
Forcing the browser to delete it. Forcing the browser to delete it.
```ts ```ts
import { Response } from "https://deno.land/std/http/server.ts";
import { delCookie } from "https://deno.land/std/http/cookie.ts"; import { delCookie } from "https://deno.land/std/http/cookie.ts";
let res = new Response(); let response: Response = {};
delCookie(res, "deno"); delCookie(response, "deno");
// Will append this header in the response
// "Set-Cookie: deno=; Expires=Thus, 01 Jan 1970 00:00:00 GMT" const cookieHeader = response.headers.get("set-cookie");
console.log("Set-Cookie:", cookieHeader);
// Set-Cookie: deno=; Expires=Thus, 01 Jan 1970 00:00:00 GMT
``` ```
**Note**: At the moment multiple `Set-Cookie` in a `Response` is not handled. **Note**: At the moment multiple `Set-Cookie` in a `Response` is not handled.