laf/docs/guide/function/function-param.md
左风 7903875218
doc: add function param and data query (#948)
* doc: add function param and data query

* doc: fix guide index
2023-03-22 21:42:32 +08:00

2.1 KiB
Raw Blame History

title
云函数参数 返回值

{{ $frontmatter.title }}

参数

main 函数中,可以通过第一个参数 ctx 来获取用户传递的请求信息。
下面的例子可以读取前端传递的 Query 参数username

exports.main = function (ctx) {
  return `hello, ${ctx.query.username}`;
};

这样可以读取前端传递的 body 参数

exports.main = function (ctx) {
  return `hello, ${ctx.body}`;
};

ctx 具有下面的一些内容:

属性 介绍
ctx.requestId 当前请求的唯一 ID
ctx.method 当前请求的方法,如GETPOST
ctx.headers 所有请求的 headers
ctx.auth 使用 Http Bearer Token 认证时,解析出的 token 值
ctx.query 当前请求的 query 参数
ctx.body 当前请求的 body 参数
ctx.response HTTP 响应,和expressResponse实例保持一致
ctx.socket WebSocket 实例
ctx.files 上传的文件 (File 对象数组)
ctx.env 自定义的环境变量 (env)

返回值

那我们如何把数据传给前端呢?很简单,只需要在云函数中 return 出去就可以了。

exports.main = function (ctx) {
  // 这里用字符串示例,你可以返回任何数据类型。
  return "这里是返回给前端的数据"
};