KScript 文档
ZH

路由与 API

响应

@response()、@view() 和 @redirect() 用于生成响应值,中间件通过 $next($request) 获得响应。你可以读取并修改它:

  • 使用 .status、.body、.type、.headers、->header(name)、.is_ok 和 ->convert(from: json) 进行读取。
  • 使用 ->with_status(code)、->with_header(name, value)、->with_type(type)、->with_etag(value) 和 ->with_cache(directives) 进行修改。每个方法都返回响应本身,因此可以链式调用。
  • ->with_cookie(name, value) 设置 Cookie,->without_cookie(name) 删除 Cookie。除非另有说明,Cookie 为 HttpOnly 且 SameSite=Lax,在 https 下为 Secure,并在浏览器关闭时失效;若要指定有效期,使用 expires::->with_cookie('theme', 'dark', expires: 30d, not http_only)。path:、domain:、secure 和 same_site: lax|strict|none 也可用。
  • ->with_header('Set-Cookie', ...) 每次调用时都会添加一个原始的 cookie 标头,而不是替换上一个,并且每个 cookie 都会作为各自独立的 Set-Cookie 标头发送。
  • @response($answer) 接收一个响应并原样返回,同时保留其状态;@response($answer, status: 410) 用于修改状态。

kscript serve 会在 HTTP 响应中发送 Server: kscript。如需为某个路由发送你自己的值,请使用 ->with_header('Server', 'my-app')。

Edit this page on GitHub