💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# API 请求 演示程序中我们封装了api请求的一些常用方法,比如`get`,`post`,`request`方法,所有请求相关的代码都在`utils/api.js`中,下面演示在`pages/demo/demo`页面 中请求一个api。 * [GET请求](https://www.kancloud.cn/thinkcmf/cmf5api/489954#GET_4) * [POST请求](https://www.kancloud.cn/thinkcmf/cmf5api/489954#POST_33) * [PUT请求 (V1.0.2新增)](https://www.kancloud.cn/thinkcmf/cmf5api/489954#PUT_V102_62) * [DELETE请求 (V1.0.2新增)](https://www.kancloud.cn/thinkcmf/cmf5api/489954#DELETE_V102_95) * [小程序登录请求](https://www.kancloud.cn/thinkcmf/cmf5api/489954#_126) ## GET请求 ``` ~~~ // 引入 api 类库 var api = require('../../utils/api.js'); Page({ onShow() { // GET请求,加载文章列表 api.get({ url: 'portal/articles', data: { page: 1, order:'-published_time' }, success: data => { console.log("文章列表数据:"); console.log(data); }, complete: () => { } }); } }); ~~~ ## POST请求 ~~~ // 引入 api 类库 var api = require('../../utils/api.js'); Page({ onShow() { // POST请求,发送手机验证码 api.post({ url: 'user/verification_code/send', data: {username: '15121000000'}, success: data => { if (data.code == 1) { // 发送成功 } if (data.code == 0) { // 发送失败 } console.log(data); } }); } }); ~~~ ## PUT请求 (V1.0.2新增) ~~~ // 引入 api 类库 var api = require('../../utils/api.js'); Page({ onShow() { // PUT请求,编辑文章 api.put({ url: 'portal/articles/1', data: { categories: '1', post_title:'文章标题', post_content:'文章内容' }, success: data => { if (data.code == 1) { // 成功 } if (data.code == 0) { // 失败 } console.log(data); } }); } }); ~~~ ## DELETE请求 (V1.0.2新增) ~~~ // 引入 api 类库 var api = require('../../utils/api.js'); Page({ onShow() { // DELETE请求,取消收藏 api.delete({ url: 'user/favorites//1', data: { }, success: data => { if (data.code == 1) { // 成功 } if (data.code == 0) { // 失败 } console.log(data); } }); } }); ~~~ ## 小程序登录请求 ~~~ // 需要用户登录的地方,调用以下方法 api.login(); ~~~ 如: ~~~ // 引入 api 类库 var api = require('../../utils/api.js'); Page({ onLoad() { try { // 判断是否登录 var isLogin = wx.getStorageSync('login'); if (!isLogin) { // 登录 api.login(); return; } } catch (e) { // Do something when catch error } }, }); ~~~ ```