### Install dependencies and start the server Source: https://github.com/aisuda/amis-admin/blob/master/README.md Install dependencies and start the development server for the amis admin template. Run these commands in the project root after cloning the repository. ```bash # 安装依赖 npm i # 打开服务 npm start ``` -------------------------------- ### Modify server port via environment variable Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/server.md Example of starting the server on a custom port using the PORT environment variable. ```bash PORT=8080 npm start # 服务输出:Web server listening on port http://localhost:8080 ``` -------------------------------- ### 设置 PORT 环境变量并启动开发服务器 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/configuration.md 使用 PORT 环境变量指定端口(默认 3000),启动 npm start 命令。输出显示服务器监听地址。 ```bash PORT=8080 npm start # Web server listening on port http://localhost:8080 ``` -------------------------------- ### Handle hot-reload startup failure Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/server.md Example of manually catching and handling errors during the hot-reload startup process. ```js const app = require('express')(); app.get('/health', (req, res) => res.send('ok')); require('reload')(app) .then(() => { const server = require('http').createServer(app); server.listen(app.get('port'), () => console.log('listening on ' + app.get('port')) ); }) .catch(err => { console.error('reload 启动失败,服务未启动', err); process.exit(1); }); ``` -------------------------------- ### PageSchema minimal example Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/types.md Minimal PageSchema example from pages/console.json. The type must be "page", title is required, and body can be a string or an array of controls. ```json { "type": "page", "title": "Dashboard", "body": "body..." } ``` -------------------------------- ### GET /* Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Fallback route serving index.html for unmatched GET requests. ```APIDOC ## GET /* ### Description Fallback route that serves `index.html` for any GET request not matching `/public` or `/pages`. It accepts any path and query string. ### Method GET ### Endpoint `/*` (including `/`) ### Parameters None (no required parameters) ### Response #### Success Response (200) - Content of `index.html` ### Authentication None ``` -------------------------------- ### GET ${API_HOST}/api/amis-mock/sample Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md List query endpoint for CRUD list page. ```APIDOC ## GET ${API_HOST}/api/amis-mock/sample ### Description List query endpoint used by the CRUD list page. The template is expanded by the renderer into query parameters. ### Method GET ### Endpoint `${API_HOST}/api/amis-mock/sample?page=${page}&perPage=${perPage}&keywords=${keywords}` ### Parameters #### Query Parameters - **page** (number) - Required - Page number for pagination. - **perPage** (number) - Required - Number of records per page. - **keywords** (string) - Optional - Search keywords. ### Response #### Success Response (200) - **data** (array) - Array of records. - **data** (object) - Pagination information (rendered as CRUD table). ``` -------------------------------- ### Initialize hot-reload server Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/server.md Starts the hot-reload service and listens on the configured port upon successful resolution. ```js reload(app) .then(function (reloadReturned) { // reloadReturned is documented in the returns API in the README server.listen(app.get('port'), function () { console.log('Web server listening on port http://localhost:' + app.get('port')); }); }) .catch(function (err) { console.error('Reload could not start, could not start server/sample app', err); }); ``` -------------------------------- ### amis Admin Initialization Source: https://github.com/aisuda/amis-admin/blob/master/index.html JavaScript setup for embedding the amis admin application, including history management and global context configuration. ```javascript (function () { let amis = amisRequire('amis/embed'); const match = amisRequire('path-to-regexp').match; // 如果想用 browserHistory 请切换下这处代码, 其他不用变 // const history = History.createBrowserHistory(); const history = History.createHashHistory(); const app = { type: 'app', brandName: 'Admin', logo: '/public/logo.png', header: { type: 'tpl', inline: false, className: 'w-full', tpl: '
顶部区域左侧
顶部区域右侧
' }, // footer: '
底部区域
', // asideBefore: '
菜单前面区域
', // asideAfter: '
菜单后面区域
', api: '/pages/site.json' }; function normalizeLink(to, location = history.location) { to = to || ''; if (to && to[0] === '#') { to = location.pathname + location.search + to; } else if (to && to[0] === '?') { to = location.pathname + to; } const idx = to.indexOf('?'); const idx2 = to.indexOf('#'); let pathname = ~idx ? to.substring(0, idx) : ~idx2 ? to.substring(0, idx2) : to; let search = ~idx ? to.substring(idx, ~idx2 ? idx2 : undefined) : ''; let hash = ~idx2 ? to.substring(idx2) : location.hash; if (!pathname) { pathname = location.pathname; } else if (pathname[0] != '/' && !/^https?:\/\//.test(pathname)) { let relativeBase = location.pathname; const paths = relativeBase.split('/'); paths.pop(); let m; while ((m = /^\.\.?\//.exec(pathname))) { if (m[0] === '../') { paths.pop(); } pathname = pathname.substring(m[0].length); } pathname = paths.concat(pathname).join('/'); } return pathname + search + hash; } function isCurrentUrl(to, ctx) { if (!to) { return false; } const pathname = history.location.pathname; const link = normalizeLink(to, { ...location, pathname, hash: '' }); if (!~link.indexOf('http') && ~link.indexOf(':')) { let strict = ctx && ctx.strict; return match(link, { decode: decodeURIComponent, strict: typeof strict !== 'undefined' ? strict : true })(pathname); } return decodeURI(pathname) === link; } let amisInstance = amis.embed( '#root', app, { location: history.location, data: { // 全局数据,是受控的数据 }, context: { // 全局上下文数据, 非受控的数据,无论哪一层都能获取到,包括弹窗自定义数据映射后都能获取到。 // 可以用来放一下全局配置等。比如 API_HOST, 这样页面配置里面可以通过 ${API_HOST} 来获取到。 API_HOST: 'https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com' } }, { // watchRouteChange: fn => { // return history.listen(fn); // }, updateLocation: (location, replace) => { location = normalizeLink(location); if (location === 'goBack') { return history.goBack(); } else if ( (!/^https?:\/\//.test(location) && location === history.location.pathname + history.location.search) || location === history.location.href ) { // 目标地址和当前地址一样,不处理,免得重复刷新 return; } else if (/^https?:\/\//.test(location) || !history) { return (window.location.href = location); } history[replace ? 'replace' : 'push'](location); }, jumpTo: (to, action) => { if (to === 'goBack') { return history.goBack(); } to = normalizeLink(to); if (isCurrentUrl(to)) { return; } if (action && action.actionType === 'url') { action.blank === false ? (window.location.href = to) : window.open(to, '_blank'); return; } else if (action && action.blank) { window.open(to, '_blank'); return; } if (/^https?:\/\//.test(to)) { window.location.href = to; } else if ( (!/^https?:\/\//.test(to) && to === history.pathname + history.location.search) || to === history.location.href ) { // do nothing } else { history.push(to); } }, isCurrentUrl: isCurrentUrl, theme: 'cxd' } ); history.listen(state => { amisInstance.updateProps({ location: state.location || state }); }); })(); ``` -------------------------------- ### GET /public/{file} Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Serves static files from the public directory. ```APIDOC ## GET /public/{file} ### Description Serves static files from the `public/` directory. The only file in this repository is `logo.png`, referenced by `AppSchema.logo` as `/public/logo.png`. ### Method GET ### Endpoint `/public/{file}` ### Parameters #### Path Parameters - **file** (string) - Required - The filename corresponding to a static file in the `public/` directory. ### Response #### Success Response (200) - File content (e.g., `logo.png`) #### Error Response (404) - File not found ### Authentication None ``` -------------------------------- ### GET ${API_HOST}/api/amis-mock/mock2/service/form?tpl=tpl3 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Fetch a remote page definition. ```APIDOC ## GET ${API_HOST}/api/amis-mock/mock2/service/form?tpl=tpl3 ### Description Fetch a remote page definition (PageSchema) for the department management page. ### Method GET ### Endpoint `${API_HOST}/api/amis-mock/mock2/service/form?tpl=tpl3` ### Parameters #### Query Parameters - **tpl** (string) - Required - Template identifier, fixed to `tpl3`. ### Response #### Success Response (200) - **status** (number) - `0` for success. - **msg** (string) - Optional message. - **data** (object) - PageSchema object. ``` -------------------------------- ### GET ${API_HOST}/api/amis-mock/sample/${params.id} Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Fetch a single record by ID for detail or edit forms. ```APIDOC ## GET ${API_HOST}/api/amis-mock/sample/${params.id} ### Description Fetch a single record by ID for detail or edit forms. The `params.id` comes from the route `/crud/:id`. ### Method GET ### Endpoint `${API_HOST}/api/amis-mock/sample/${params.id}` ### Parameters #### Path Parameters - **id** (string) - Required - The record ID. ### Response #### Success Response (200) - **status** (number) - `0` for success. - **msg** (string) - Optional message. - **data** (object) - Single record data, used to fill form controls. ``` -------------------------------- ### GET /pages/{file} Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Serves static files from the pages directory. ```APIDOC ## GET /pages/{file} ### Description Serves static files from the `pages/` directory, including `.json` page definitions and `jsonp.js`. The `Content-Type` is inferred by Express from the file extension (e.g., `application/json` or `text/javascript`). ### Method GET ### Endpoint `/pages/{file}` ### Parameters #### Path Parameters - **file** (string) - Required - The filename corresponding to a file in the `pages/` directory. ### Response #### Success Response (200) - File content with appropriate `Content-Type` #### Error Response (404) - File not found ### Authentication None ``` -------------------------------- ### FormControl date-range example Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/types.md A date-range control example from pages/form-basic.json. Uses type "date-range" with a remark field. ```json { "label": "活动时间", "type": "date-range", "name": "range", "size": "md", "remark": "这是一个字段时间范围" } ``` -------------------------------- ### 完整的 Express 开发服务器(server.js) Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/server.md 副作用模块,执行后启动 Web 服务器,监听 PORT 环境变量或默认端口 3000。静态托管 public/ 和 pages/ 目录,所有 GET 请求回退到 index.html。集成 reload 以实现热重载;如果 reload 启动失败,记录错误并停止服务器启动。 ```javascript // server.js(完整,37 行) const express = require('express'); const http = require('http'); const path = require('path'); const reload = require('reload'); const bodyParser = require('body-parser'); const logger = require('morgan'); const app = express(); app.set('port', process.env.PORT || 3000); // L10 app.use(logger('dev')); // L11 app.use(bodyParser.json()); // L12 app.use('/public', express.static('public')); // L14 app.use('/pages', express.static('pages')); // L15 app.get('/*', function (req, res) { // L17 res.sendFile(path.join(__dirname, 'index.html')); }); const server = http.createServer(app); // L21 reload(app) .then(function (reloadReturned) { // L25 server.listen(app.get('port'), function () { // L29 console.log( 'Web server listening on port http://localhost:' + app.get('port') ); }); }) .catch(function (err) { // L35 console.error( 'Reload could not start, could not start server/sample app', err ); }); ``` -------------------------------- ### FormControl text example Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/types.md A representative text control from pages/form-basic.json. Shows required, placeholder, size, validations with matchRegexp, custom validationErrors, and hint. ```json { "label": "编号", "required": true, "type": "text", "placeholder": "请输入编号", "name": "b", "size": "md", "validations": { "matchRegexp": "/^\\w{4}-\\w{4}-\\w{4}$/" }, "validationErrors": { "matchRegexp": "您输入的内容格式不对,请按提示输入!" }, "hint": "输入范例:xxxx-xxxx-xxxx" } ``` -------------------------------- ### Define SPA fallback route Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/server.md Matches all GET requests not handled by previous middleware and serves the index.html file. ```js app.get('/*', function (req, res) { res.sendFile(path.join(__dirname, 'index.html')); }); ``` -------------------------------- ### POST ${API_HOST}/api/amis-mock/sample Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Create a new record via form submission. ```APIDOC ## POST ${API_HOST}/api/amis-mock/sample ### Description Create a new record. The method is determined by the amis renderer (default POST for form submission). The request body contains form fields. ### Method POST ### Endpoint `${API_HOST}/api/amis-mock/sample` ### Parameters #### Request Body - **engine** (string) - Required - Engine field. - **browser** (string) - Required - Browser field. - **platform** (string) - Required - Platform field. - **version** (string) - Required - Version field. - **grade** (string) - Required - Grade field. ### Response #### Success Response (200) - **status** (number) - `0` for success. - **msg** (string) - Optional message. - **data** (object) - Optional data. ``` -------------------------------- ### POST ${API_HOST}/api/amis-mock/saveWizard Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Save wizard form data. ```APIDOC ## POST ${API_HOST}/api/amis-mock/saveWizard ### Description Save wizard form data. The request body contains merged fields from all steps. ### Method POST ### Endpoint `${API_HOST}/api/amis-mock/saveWizard` ### Parameters #### Request Body - **title** (string) - Required - Title field. - **date** (string) - Required - Date field. - **num** (number) - Required - Number field. - **company** (string) - Required - Company field. - **money** (number) - Required - Money field. ### Response #### Success Response (200) - **status** (number) - `0` for success. - **msg** (string) - Optional message. - **data** (object) - Optional data. ``` -------------------------------- ### history.listen(callback) Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 订阅路由变化,当路由状态变化时执行回调函数。返回取消订阅函数。 ```APIDOC ## history.listen(callback) ### Description 订阅路由变化,当路由状态变化时执行回调函数。返回取消订阅函数。 ### Method listen ### Endpoint history.listen(callback) ### Parameters #### callback ((state) => void) - Required - 状态变化回调;state 含 location(当回调直接传 location 时 state.location 可能不存在,源码做了 || state 兜底) ### Request Example history.listen(state => { amisInstance.updateProps({ location: state.location || state }); }); ### Response #### Success Response - 返回取消订阅函数(本仓库未使用返回值;源码注释表明其可回传给 embed 的 watchRouteChange 选项)。 ``` -------------------------------- ### Serve static files from public directory Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Serves static files from the 'public' directory at the '/public' path. No authentication is required. Returns the file content with a 200 status on hit, or 404 if the file does not exist. ```javascript app.use('/public', express.static('public')); ``` -------------------------------- ### POST ${API_HOST}/api/amis-mock/sample/bulkUpdate2 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Batch update records. ```APIDOC ## POST ${API_HOST}/api/amis-mock/sample/bulkUpdate2 ### Description Batch update endpoint used by the bulk edit dialog in the CRUD list page. ### Method POST ### Endpoint `${API_HOST}/api/amis-mock/sample/bulkUpdate2` ### Parameters #### Request Body - **engine** (string) - Required - Example field for batch edit. ### Response #### Success Response (200) - **status** (number) - `0` for success. - **msg** (string) - Optional message. - **data** (object) - Optional data. ``` -------------------------------- ### history.listen 订阅路由变化 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 订阅路由状态变化,并在回调中更新渲染器属性。 ```js history.listen(state => { amisInstance.updateProps({ location: state.location || state }); }); ``` -------------------------------- ### Initialize Express app instance Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/server.md The internal Express application instance used for routing and middleware registration. ```js const app = express(); ``` -------------------------------- ### CSS Styles for App Wrapper Source: https://github.com/aisuda/amis-admin/blob/master/index.html Basic CSS to ensure the application wrapper occupies the full viewport. ```css html, body, .app-wrapper { position: relative; width: 100%; height: 100%; margin: 0; padding: 0; } ``` -------------------------------- ### AmisEmbedOptions 实参定义 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/types.md 用于 amis.embed 的第三参数,定义全局数据与上下文。location 为当前路由地址对象,data 为受控全局数据(此处为空对象),context 为非受控全局上下文,支持 ${KEY} 模板取值,此处定义 API_HOST 供页面/表单通过 ${API_HOST}/api/amis-mock/... 引用。 ```javascript { location: history.location, data: { // 全局数据,是受控的数据 }, context: { // 非受控的数据... 页面配置里面可以通过 ${API_HOST} 来获取到 API_HOST: 'https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com' } } ``` -------------------------------- ### 加载 amis SDK 及运行时依赖 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 在 HTML 中引入 amis 3.2.0 SDK 样式与脚本,以及 Vue 2 和 History 4.10.1 运行时依赖。amis SDK 必须整体加载以确保样式与功能正常。 ```html ``` -------------------------------- ### Configure and retrieve server port Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/server.md Sets the server port using environment variables or a default value, and retrieves it for the server listener. ```js app.set('port', process.env.PORT || 3000); // ... server.listen(app.get('port'), function () { ... }); ``` -------------------------------- ### JSONP /pages/jsonp.js?callback=jsonpCallback Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Load a page definition via JSONP. ```APIDOC ## JSONP /pages/jsonp.js?callback=jsonpCallback ### Description Load a page definition via JSONP. The script calls the global `jsonpCallback` with the page schema. ### Method JSONP ### Endpoint `jsonp:/pages/jsonp.js?callback=jsonpCallback` ### Parameters #### Query Parameters - **callback** (string) - Required - The name of the global callback function. ### Response #### Success Response (200) - Script that calls `jsonpCallback({ data: PageSchema, status: 0 })`. ``` -------------------------------- ### amisRequire 模块加载器 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 用于加载 SDK 内置模块,如 'amis/embed' 渲染器对象或 'path-to-regexp' 路径匹配函数。 ```js let amis = amisRequire('amis/embed'); const match = amisRequire('path-to-regexp').match; ``` -------------------------------- ### AmisEmbedSettings 实参定义 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/types.md 用于 amis.embed 的第四参数,定义路由与主题设置。watchRouteChange 为注释示例,正文改用外部 history.listen;updateLocation 处理地址更新,jumpTo 处理跳转,isCurrentUrl 判定当前地址,theme 为 'cxd'。 ```javascript { // watchRouteChange: fn => { // return history.listen(fn); // }, updateLocation: (location, replace) => { ... }, jumpTo: (to, action) => { ... }, isCurrentUrl: isCurrentUrl, theme: 'cxd' } ``` -------------------------------- ### PUT ${API_HOST}/api/amis-mock/sample/$id Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Update an existing record. ```APIDOC ## PUT ${API_HOST}/api/amis-mock/sample/$id ### Description Update an existing record. The `$id` is a form data variable. The method is determined by the amis renderer (default POST for form submission, but this endpoint is for update). ### Method PUT ### Endpoint `${API_HOST}/api/amis-mock/sample/$id` ### Parameters #### Path Parameters - **id** (string) - Required - The record ID (from form data variable `$id`). #### Request Body - Form fields to update (e.g., `engine`, `browser`, etc.) ### Response #### Success Response (200) - **status** (number) - `0` for success. - **msg** (string) - Optional message. - **data** (object) - Optional data. ``` -------------------------------- ### nodemon.json 完整配置 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/configuration.md 开发工具 nodemon 的配置文件,启用冗长输出并忽略 node_modules 目录以避免依赖触发重启。 ```json { "verbose": true, "ignore": ["node_modules/*"] } ``` -------------------------------- ### pages/jsonp.js 模块实现 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/jsonp.md 模块通过 IIFE 执行,构造包含 PageSchema 的响应对象,并调用全局 jsonpCallback 函数。 ```javascript (function() { const response = { data: { type: "page", title: "标题", body: "this result is from jsonp" }, status: 0 } window.jsonpCallback && window.jsonpCallback(response); })(); ``` -------------------------------- ### 定义全局上下文 API_HOST Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/configuration.md 在 index.html L133-136 中定义 context 对象,设置 API_HOST 为后端地址。任意页面配置可通过 ${API_HOST} 模板引用,切换后端时只需修改此处。 ```javascript context: { API_HOST: 'https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com' } ``` -------------------------------- ### amis.embed(selector, schema, options, settings) Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 嵌入 amis 渲染器到指定 DOM 容器,并返回渲染器实例。该实例可用于后续更新属性。 ```APIDOC ## amis.embed(selector, schema, options, settings) ### Description 嵌入 amis 渲染器到指定 DOM 容器,并返回渲染器实例。该实例可用于后续更新属性。 ### Method embed ### Endpoint amis.embed(selector, schema, options, settings) ### Parameters #### selector (string) - Required - 渲染容器的 CSS 选择器,本仓库为 '#root' #### schema (AppSchema) - Required - 应用外壳 schema(见 types.md 的 AppSchema) #### options (object) - Required - 包含 location(history.location)、data(受控全局数据,源码中为空对象)、context(非受控全局上下文,源码中定义 API_HOST,页面配置可用 ${API_HOST} 引用,如 ${API_HOST}/api/amis-mock/sample) #### settings (object) - Required - 路由与外观设置:updateLocation、jumpTo、isCurrentUrl、theme: 'cxd';另有被注释的 watchRouteChange 选项(对应 history.listen 的返回) ### Request Example let amisInstance = amis.embed( '#root', app, { location: history.location, data: { // 全局数据,是受控的数据 }, context: { API_HOST: 'https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com' } }, { updateLocation: (location, replace) => { ... }, jumpTo: (to, action) => { ... }, isCurrentUrl: isCurrentUrl, theme: 'cxd' } ); ### Response #### Success Response - 返回渲染器实例,存在 updateProps(props) 方法。 #### Response Example let amisInstance = amis.embed('#root', app, options, settings); history.listen(state => { amisInstance.updateProps({ location: state.location || state }); }); ``` -------------------------------- ### Serve static files from pages directory Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Serves static files from the 'pages' directory at the '/pages' path. No authentication is required. Content-Type is inferred by Express from the file extension (e.g., application/json or text/javascript). Returns 200 on hit, 404 if the file does not exist. ```javascript app.use('/pages', express.static('pages')); ``` -------------------------------- ### SitePageNavItem 带子菜单示例 (pages/site.json) Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/types.md SitePageNavItem 复杂示例,包含 rewrite、icon 和 children 子菜单,子菜单使用 schemaApi 加载页面定义。 ```json { "label": "列表示例", "url": "/crud", "rewrite": "/crud/list", "icon": "fa fa-cube", "children": [ { "label": "列表", "url": "/crud/list", "icon": "fa fa-list", "schemaApi": "get:/pages/crud-list.json" } ] } ``` -------------------------------- ### POST ${API_HOST}/api/amis-mock/form/save Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Save form data for basic and advanced forms. ```APIDOC ## POST ${API_HOST}/api/amis-mock/form/save ### Description Save form data. Used by basic and advanced forms. The request body contains all form fields. ### Method POST ### Endpoint `${API_HOST}/api/amis-mock/form/save` ### Parameters #### Request Body - **title** (string) - Required - Title field. - **b** (string) - Required - Field b. - **c** (string) - Required - Field c. - **range** (string) - Required - Range field. - **start** (string) - Required - Start date. - **end** (string) - Required - End date. - **browser** (string) - Required - Browser field. - **taocan** (string) - Required - Taocan field. - **select** (string) - Required - Select field. - **freeday** (string) - Required - Freeday field. - **num** (number) - Required - Number field. - **percent** (number) - Required - Percent field. - **textarea** (string) - Required - Textarea field. - **description** (string) - Optional - Description field (advanced form). - **repeat** (string) - Optional - Repeat field (advanced form). - **time** (string) - Optional - Time field (advanced form). - **weekdays** (array) - Optional - Weekdays field (advanced form). - **monthday** (string) - Optional - Monthday field (advanced form). - **admins[]** (array) - Optional - Admins array (advanced form). - **thetable** (array) - Optional - Table field (advanced form). ### Response #### Success Response (200) - **status** (number) - `0` for success. - **msg** (string) - Optional message. - **data** (object) - Optional data. ``` -------------------------------- ### AppSchema: Define the amis app shell with brandName, header, and api Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/types.md Defines the AppSchema object used as the `schema` argument to `amis.embed`. The `type` and `api` fields are the minimal required configuration for the app to run; other fields are optional and can be removed. The commented-out fields (`footer`, `asideBefore`, `asideAfter`) are optional and not used in the repository. ```javascript const app = { type: 'app', brandName: 'Admin', logo: '/public/logo.png', header: { type: 'tpl', inline: false, className: 'w-full', tpl: '
顶部区域左侧
顶部区域右侧
' }, // footer: '
底部区域
', // asideBefore: '
菜单前面区域
', // asideAfter: '
菜单后面区域
', api: '/pages/site.json' }; ``` -------------------------------- ### JSONP 页面配置引用 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/jsonp.md 在 site.json 中通过 schemaApi 使用 jsonp: 协议引用页面,并指定回调函数名。 ```json { "label": "jsonp 返回示例", "schemaApi": "jsonp:/pages/jsonp.js?callback=jsonpCallback" } ``` -------------------------------- ### History 路由历史工厂 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 创建路由历史实例。默认使用 Hash 路由,可通过切换注释行改为 Browser 路由。 ```js // 如果想用 browserHistory 请切换下这处代码, 其他不用变 // const history = History.createBrowserHistory(); const history = History.createHashHistory(); ``` -------------------------------- ### 浏览器手动验证 JSONP 回调 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/jsonp.md 通过在浏览器中模拟渲染器注入的回调函数,验证 JSONP 响应数据的结构与内容。 ```html ``` -------------------------------- ### SitePageNavItem 简单示例 (pages/site.json) Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/types.md SitePageNavItem 示例,包含 label、url 和 redirect 字段,redirect 将根路径重定向到 /index/1。 ```json { "label": "Home", "url": "/", "redirect": "/index/1" } ``` -------------------------------- ### amisInstance.updateProps 更新渲染器属性 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 通过 updateProps 方法将 history 的状态变化回写进渲染器,实现地址变化驱动页面切换。 ```js history.listen(state => { amisInstance.updateProps({ location: state.location || state }); }); ``` -------------------------------- ### AmisApiEnvelope 响应对象 (pages/jsonp.js) Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/types.md 定义于 pages/jsonp.js,用于 jsonp: 协议装载,data 为 PageSchema 页面定义,status 为 0 表示成功。 ```javascript const response = { data: { type: "page", title: "标题", body: "this result is from jsonp" }, status: 0 } ``` -------------------------------- ### DELETE ${API_HOST}/api/amis-mock/sample/$ids Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Batch delete records. ```APIDOC ## DELETE ${API_HOST}/api/amis-mock/sample/$ids ### Description Batch delete records. The `$ids` is a collection of primary keys of selected rows. A confirmation dialog is shown before the request. ### Method DELETE ### Endpoint `${API_HOST}/api/amis-mock/sample/$ids` ### Parameters #### Path Parameters - **ids** (string) - Required - Comma-separated list of record IDs to delete. ### Response #### Success Response (200) - **status** (number) - `0` for success. - **msg** (string) - Optional message. - **data** (object) - Optional data. ``` -------------------------------- ### amis.embed 嵌入渲染器 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 使用 amis.embed 将渲染器嵌入到指定的 DOM 容器中,并配置全局数据、上下文及路由设置。 ```js let amisInstance = amis.embed( '#root', app, { location: history.location, data: { // 全局数据,是受控的数据 }, context: { API_HOST: 'https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com' } }, { updateLocation: (location, replace) => { ... }, jumpTo: (to, action) => { ... }, isCurrentUrl: isCurrentUrl, theme: 'cxd' } ); ``` -------------------------------- ### Register middleware chain Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/server.md Registers logging, body parsing, and static file serving middleware in the application. ```js app.use(logger('dev')); app.use(bodyParser.json()); // Parses json, multi-part (file), url-encoded app.use('/public', express.static('public')); app.use('/pages', express.static('pages')); ``` -------------------------------- ### .prettierrc 完整配置 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/configuration.md Prettier 代码格式化配置,设置行宽、缩进、引号、分号、尾随逗号等规则。 ```json { "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "semi": true, "trailingComma": "none", "bracketSpacing": false, "quoteProps": "consistent", "arrowParens": "avoid", "jsxBracketSameLine": false } ``` -------------------------------- ### watchRouteChange 等效写法示例 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 展示了如何通过 watchRouteChange 选项结合 history.listen 实现路由监听的等效写法。 ```js // watchRouteChange: fn => { // return history.listen(fn); // } ``` -------------------------------- ### DELETE ${API_HOST}/api/amis-mock/sample/$id Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/endpoints.md Delete a single record. ```APIDOC ## DELETE ${API_HOST}/api/amis-mock/sample/$id ### Description Delete a single record. A confirmation dialog is shown before the request. ### Method DELETE ### Endpoint `${API_HOST}/api/amis-mock/sample/$id` ### Parameters #### Path Parameters - **id** (string) - Required - The record ID to delete. ### Response #### Success Response (200) - **status** (number) - `0` for success. - **msg** (string) - Optional message. - **data** (object) - Optional data. ``` -------------------------------- ### 手动刷新 location 示例 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 在 embed 之后,通过监听 history 的变化手动调用 updateProps 来更新渲染器位置信息。 ```js let amisInstance = amis.embed('#root', app, options, settings); history.listen(state => { amisInstance.updateProps({ location: state.location || state }); }); ``` -------------------------------- ### amisInstance.updateProps(props) Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 更新渲染器属性,将 history 的每次状态变化回写进渲染器,实现地址变化驱动页面切换。 ```APIDOC ## amisInstance.updateProps(props) ### Description 更新渲染器属性,将 history 的每次状态变化回写进渲染器,实现地址变化驱动页面切换。 ### Method updateProps ### Endpoint amisInstance.updateProps(props) ### Parameters #### props (object) - Required - 需回写的渲染器属性;本仓库写入 location: state.location || state(history.listen 的回调参数可能直接是 location 对象) ### Request Example history.listen(state => { amisInstance.updateProps({ location: state.location || state }); }); ### Response #### Success Response - 返回:无(源码未使用返回值)。 ``` -------------------------------- ### AmisApiEnvelope 顶层结构 (pages/site.json) Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/types.md 顶层结构定义于 pages/site.json,status 为 0 表示成功,msg 为空字符串,data 为 SitePages 导航清单。 ```json { "status": 0, "msg": "", "data": { "pages": [ ... ] } } ``` -------------------------------- ### isCurrentUrl 当前地址判定 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 判断目标地址是否为当前页面。支持使用 path-to-regexp 进行路由匹配。 ```js function isCurrentUrl(to, ctx) { if (!to) { return false; } const pathname = history.location.pathname; const link = normalizeLink(to, { ...location, pathname, hash: '' }); if (!~link.indexOf('http') && ~link.indexOf(':')) { let strict = ctx && ctx.strict; return match(link, { decode: decodeURIComponent, strict: typeof strict !== 'undefined' ? strict : true })(pathname); } return decodeURI(pathname) === link; } ``` ```js let amisInstance = amis.embed('#root', app, options, { updateLocation: ..., jumpTo: ..., isCurrentUrl: isCurrentUrl, // L194 theme: 'cxd' }); ``` -------------------------------- ### normalizeLink 链接归一化工具 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/index.md 将相对路径、hash 或 query 转换为完整的规范化地址字符串。 ```js function normalizeLink(to, location = history.location) { to = to || ''; if (to && to[0] === '#') { to = location.pathname + location.search + to; } else if (to && to[0] === '?') { to = location.pathname + to; } const idx = to.indexOf('?'); const idx2 = to.indexOf('#'); let pathname = ~idx ? to.substring(0, idx) : ~idx2 ? to.substring(0, idx2) : to; let search = ~idx ? to.substring(idx, ~idx2 ? idx2 : undefined) : ''; let hash = ~idx2 ? to.substring(idx2) : location.hash; if (!pathname) { pathname = location.pathname; } else if (pathname[0] != '/' && !/^https?\:\/\//.test(pathname)) { let relativeBase = location.pathname; const paths = relativeBase.split('/'); paths.pop(); let m; while ((m = /^\.\.?\//.exec(pathname))) { if (m[0] === '../') { paths.pop(); } pathname = pathname.substring(m[0].length); } pathname = paths.concat(pathname).join('/'); } return pathname + search + hash; } ``` ```js // 假定 history.location = { pathname: '/crud/list', search: '', hash: '' } normalizeLink('../new'); // => '/crud/new' normalizeLink('?keywords=amis'); // => '/crud/list?keywords=amis' normalizeLink('#detail'); // => '/crud/list#detail' normalizeLink('/pages/site.json'); // => '/pages/site.json' normalizeLink(''); // => '/crud/list'(当前 pathname) ``` -------------------------------- ### 自定义页面数据返回示例 Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/api-reference/jsonp.md 修改 response.data 结构以返回自定义的页面内容,同时保持 status 为 0。 ```javascript (function() { const response = { data: { type: "page", title: "我的页面", body: [ { "type": "static", "name": "engine", "label": "Engine" } ] }, status: 0 } window.jsonpCallback && window.jsonpCallback(response); })(); ``` -------------------------------- ### OptionItem JSON shapes from crud-advance.json and form-basic.json Source: https://github.com/aisuda/amis-admin/blob/master/_autodocs/types.md Three JSON object shapes for OptionItem as defined in pages/crud-advance.json and pages/form-basic.json. The first shows a simple label/value pair; the second shows a disabled option with HTML body content for the list control; the third shows a value with a label that matches the value, used when label is missing. ```json { "label": "每天", "value": "day" } ``` ```json { "value": 3, "disabled": true, "body": "
套餐:C03 ...
" } ``` ```json { "value": 7, "label": "07" } // 同时存在缺省 label 的场景(crud-advance.json monthday 选项) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.