Get started
云代码函数
12 分
云代码 是一个强大的工具,使您能够直接在服务器上执行javascript函数,为您的应用程序添加高级功能,而无需管理自己的服务器。在back4app的环境中运行确保了可扩展性和简便性。 使用云代码,您可以: 自动化数据库操作以响应事件。 为请求创建自定义验证。 使用npm库将您的应用程序与外部服务集成。 先决条件 要完成本教程,您需要在back4app上创建一个应用程序。 请按照 创建新应用程序教程 了解如何在back4app上创建应用程序。 目标 从您的应用程序部署和执行云函数 1 访问您的云代码 转到您的back4app仪表板中的 云代码 部分。您会找到两个主要文件夹: cloud 和 public 2 编辑 main js 文件 main js 文件是定义您的云代码函数的地方。 如果需要,您可以使用以下方式从其他文件导入函数: main js require(' /filename js'); 3 创建您的第一个云代码函数 一些基本的函数示例包括: 一个简单的问候函数: main js parse cloud define("hello", async (request) => { console log("hello from cloud code!"); return "hello from cloud code!"; }); 一个求和两个数字的函数: parse cloud define("sumnumbers", async (request) => { return request params number1 + request params number2; }); 4 将你的代码部署到服务器 一旦您的函数准备就绪,点击 deploy 按钮将它们发布到 back4app 环境。 5 测试您的云代码函数 您可以通过 api 使用 curl 或任何首选 sdk 直接测试您的函数。以下是调用 hello 函数的示例: parse cloud run('hello') then((result) => { console log(result); // output "hello from cloud code!" }) catch((error) => { console error('error ', error); }); flutter parsecloudfunction function = parsecloudfunction('hello'); parseresponse response = await function execute(); if (response success) { print(response result); // output "hello from cloud code!" } else { print('error ${response error message}'); } android parsecloud callfunctioninbackground("hello", new hashmap<>(), new functioncallback\<object>() { @override public void done(object result, parseexception e) { if (e == null) { log d("cloud code", result tostring()); // output "hello from cloud code!" } else { log e("cloud code error", e getmessage()); } } }); ios parsecloud callfunction("hello", parameters nil) { result in switch result { case success(let response) print("response \\(response)") // output "hello from cloud code!" case failure(let error) print("error \\(error localizeddescription)") } } net var result = await parsecloud callfunctionasync\<string>("hello", null); console writeline(result); // output "hello from cloud code!"use parse\parsecloud; try { $result = parsecloud run("hello"); echo $result; // output "hello from cloud code!" } catch (exception $ex) { echo "error " $ex >getmessage(); } rest api curl x post \\ h "x parse application id application id" \\ h "x parse rest api key rest api key" \\ \ data urlencode "" \\ https //parseapi back4app com/functions/hello 6 附加功能 数据操作 使用特定功能创建、编辑或检索数据库中的对象,例如创建待办事项的示例 main js parse cloud define("createtodo", async (request) => { const todo = new parse object('todo'); todo set('title', request params title); todo set('done', request params done); return await todo save(); }); 高级查询 直接从数据库中检索信息 main js parse cloud define("getlisttodo", async (request) => { const query = new parse query("todo"); query equalto("done", true); query descending("title"); return await query find(); }); 结论 使用云代码,您可以轻松构建强大且定制的解决方案。它非常适合自动化、集成和验证,并与任何技术(如flutter、react native或rest api)无缝协作。 如果您遇到任何问题, back4app支持团队 随时可以为您提供帮助。