乐闻世界logo
搜索文章和话题

How to Set multiple cookie headers in Koa

1个答案

1

Setting multiple cookies in Koa is straightforward. Koa's built-in ctx.cookies.set(name, value, [options]) method simplifies handling cookies on the server. To set multiple cookies, simply call this method multiple times.

Below is a specific example demonstrating how to set multiple cookies in a simple Koa application:

javascript
const Koa = require('koa'); const app = new Koa(); app.use(async ctx => { // Set the first cookie ctx.cookies.set('username', 'JohnDoe', { httpOnly: true, // Enhances security by preventing JavaScript access expires: new Date(Date.now() + 24 * 60 * 60 * 1000) // Sets expiration to one day from now }); // Set the second cookie ctx.cookies.set('session_id', 'xyz123', { secure: true, // Sends only over HTTPS connections maxAge: 3600000 // Sets maximum age to 1 hour }); ctx.body = 'Cookies are set.'; }); app.listen(3000);

In the above code, we create a Koa application and set two cookies within the middleware. Each ctx.cookies.set call configures a single cookie, and you can customize specific options as needed, such as httpOnly, expires, secure, and maxAge.

Overall, setting multiple cookies involves calling ctx.cookies.set multiple times and tailoring each cookie's behavior through options. This approach provides flexible handling of multiple cookies while allowing you to configure security settings based on your application's requirements.

2024年6月29日 12:07 回复

你的答案