NocoBase RunJS ctx.request() 实战指南在 JS 代码中发起带认证的 HTTP 请求【免费下载链接】nocobaseNocoBase is an open-source AI no-code platform for building business systems fast. Instead of generating everything from scratch, AI works on top of production-proven infrastructure and a WYSIWYG no-code interface, so you get both speed and reliability.项目地址: https://gitcode.com/GitHub_Trending/no/nocobasectx.request()是 NocoBase RunJS 运行时JSBlock、JSField、JSAction、事件流、联动等场景中发起 HTTP 请求的统一入口。它会自动携带当前应用的 baseURL、Token、locale、role 等认证与本地化信息并沿用应用内置的请求拦截与错误处理逻辑。读完本文你将掌握资源风格 URL、常用参数、响应结构解析、跨域请求与错误静默等完整用法并能结合源码理解其底层实现原理。适用场景凡是 RunJS 中需要发起远程 HTTP 请求的场景都可以使用ctx.request()典型包括JSBlock在页面区块中通过脚本拉取数据并渲染JSField / JSItem / JSColumn字段级、条目级、列级脚本中的动态数据获取JSAction / 事件流 / 联动在动作或联动逻辑中调用后端接口、提交数据。与直接使用fetch或axios不同ctx.request()会自动复用应用级的认证上下文你无需手工拼接 Token 或处理 401 跳转。类型定义ctx.request的类型定义为request(options: RequestOptions): PromiseAxiosResponseany;其中RequestOptions在 Axios 的AxiosRequestConfig基础上扩展了两个 NocoBase 专属字段type RequestOptions AxiosRequestConfig { skipNotify?: boolean | ((error: any) boolean); // 请求失败时是否跳过全局错误提示 skipAuth?: boolean; // 是否跳过认证跳转如 401 不跳转登录页 };在源码中RequestOptions类型由nocobase/sdk导出RunJS 引擎在 packages/core/flow-engine/src/flowContext.ts 中声明request: (options: RequestOptions) Promiseany并在defineMethod(request, ...)中完成实现flowContext.ts。常用参数参数类型说明urlstring请求 URL。支持资源风格如users:list、posts:create或完整 URLmethodget | post | put | patch | deleteHTTP 方法默认getparamsobject查询参数序列化到 URLdataany请求体用于 post/put/patchheadersobject自定义请求头skipNotifyboolean | (error) boolean为 true 或函数返回 true 时失败不弹出全局错误提示skipAuthboolean为 true 时 401 等不触发认证跳转如跳转登录页说明skipNotify支持传入函数函数接收错误对象并返回布尔值因此可以按错误类型精细控制是否弹出全局提示例如仅忽略取消类错误。资源风格 URLNocoBase 资源 API 支持资源:动作的简写形式ctx.request()同样支持格式说明示例collection:action单表 CRUDusers:list、users:get、users:create、posts:updatecollection.relation:action关联资源需通过resourceOf或 URL 传主键posts.comments:list相对路径会与应用的 baseURL通常为/api拼接跨域需使用完整 URL目标服务需配置 CORS。底层路由逻辑在 flowContext.ts 中定义了shouldBypassApiClient判断函数当url以http:/https:开头且请求的 origin 与应用的 API origin 不同、或请求路径不以 API 路径为前缀时判断为跨域请求ctx.request会直接走axios.request(options)裸请求flowContext.ts否则走this.api.request(options)由应用级 APIClient 统一处理认证头、拦截器与错误提示。响应结构返回值为 Axios 响应对象常用字段response.data响应体列表接口通常为data.data记录数组data.meta分页等单条/创建/更新接口多为data.data为单条记录。示例列表查询const { data } await ctx.request({ url: users:list, method: get, params: { pageSize: 10, page: 1 }, }); const rows Array.isArray(data?.data) ? data.data : []; const meta data?.meta; // 分页等信息提交数据const res await ctx.request({ url: users:create, method: post, data: { nickname: 张三, email: zhangsanexample.com }, }); const newRecord res?.data?.data;带筛选与排序const res await ctx.request({ url: users:list, method: get, params: { pageSize: 20, sort: [-createdAt], filter: { status: active }, }, });sort支持数组写法字段前加-表示倒序filter为 NocoBase 的过滤语法对象。跳过错误提示const res await ctx.request({ url: some:action, method: get, skipNotify: true, // 失败时不弹出全局 message }); // 或按错误类型决定是否跳过 const res2 await ctx.request({ url: some:action, method: get, skipNotify: (err) err?.name CanceledError, });skipNotify的判定逻辑在客户端 APIClient.ts 的handleNotificationError中实现它会读取error.config?.skipNotify若为 true 或为函数且对当前错误返回 true则直接抛出错误、不触发全局错误提示。跨域请求使用完整 URL 请求其他域名时目标服务需配置 CORS 允许当前应用来源。若目标接口需自己的 token可通过 headers 传入const res await ctx.request({ url: https://api.example.com/v1/data, method: get, }); const res2 await ctx.request({ url: https://api.other.com/items, method: get, headers: { Authorization: Bearer 目标服务的 token, }, });注意跨域请求走的是裸axios.request不会自动附带当前应用的 Token需要按需在headers中手动传入目标服务的凭证。配合 ctx.render 展示const { data } await ctx.request({ url: users:list, method: get, params: { pageSize: 5 }, }); const rows Array.isArray(data?.data) ? data.data : []; ctx.render([ div stylepadding:12px, h4 ctx.t(用户列表) /h4, ul, ...rows.map((r) li (r.nickname ?? r.username ?? ) /li), /ul, /div, ].join());认证与请求头注入原理同域请求会自动携带当前用户的认证与本地化信息其来源是 APIClient 的getHeaders()实现packages/core/sdk/src/APIClient.tsgetHeaders() { const headers {}; if (this.auth.locale) { headers[X-Locale] this.auth.locale; } if (this.auth.role) { headers[X-Role] this.auth.role; } if (this.auth.authenticator) { headers[X-Authenticator] this.auth.authenticator; } if (this.auth.token) { headers[Authorization] Bearer ${this.auth.token}; } return headers; }即请求会自动携带Authorization: Bearer token当前用户凭证X-Locale当前语言如zh-CN、en-USX-Role当前角色X-Authenticator认证方式。客户端 APIClient.ts 在请求拦截器中把这些头合并进请求且仅当自定义 headers 未设置同名头时才覆盖保证你手动传入的Authorization等字段优先生效。注意事项错误处理请求失败会抛出异常默认会弹出全局错误提示。使用skipNotify: true可自行捕获并处理。在 APIClient.ts 中应用还会针对TOKEN_INVALID、USER_LOCKED、ROLE_NOT_FOUND_ERR等错误码做 Token/角色清理与页面刷新等特殊处理APIClient.ts。认证同域请求会自动携带当前用户的 Token、locale、role跨域需目标支持 CORS并按需在 headers 中传入 token。资源权限请求受 ACL 约束仅能访问当前用户有权限的资源。相关ctx.message - 请求完成后展示轻量提示ctx.notification - 请求完成后展示通知ctx.render - 将请求结果渲染到界面ctx.makeResource - 构建资源对象用于链式数据加载与直接ctx.request二选一【免费下载链接】nocobaseNocoBase is an open-source AI no-code platform for building business systems fast. Instead of generating everything from scratch, AI works on top of production-proven infrastructure and a WYSIWYG no-code interface, so you get both speed and reliability.项目地址: https://gitcode.com/GitHub_Trending/no/nocobase创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考