This article introduces the small program call API interface package, and through KOA2 write a test interface call.

Base directory

├ ─ ─ API │ └ ─ ─ API. Js / / interface configuration ├ ─ ─ pages │ ├ ─ ─ index / / test page │ │ ├ ─ ─ index. The js │ │ ├ ─ ─ index. The json │ │ ├ ─ ─ but WXML │ │ └ ─ ─ index. WXSS ├ ─ ─ utils │ └ ─ ─ util. Js...Copy the code

./api/api

// Define the base URL
const BASE_URL = 'http://0.0.0.0:3000';

// Encapsulate the request
const request = (url, method, data) = > {
  return new Promise((resolve, reject) = > {
    wx.request({
      url: BASE_URL + '/api/v2'  + url,
      method: method,
      data: data || {},
      header: {
        Accept: "application/json".'Content-Type': 'application/x-www-form-urlencoded'
      },
      success(request) {
        resolve(request.data)
      },
      fail(error) {
        reject(error)
      },
      complete(res) {
        console.log('loading completed'); }})})}// Extend promise's finally method
Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value= > {
      P.resolve(callback()).then(() = > value);
    },
    reason= > {
      P.resolve(callback()).then( () = > { throwreason }); }); }// Export interface
module.exports = {
  // Test the interface
  test(params){
    return request('/test'.'post', params); }}Copy the code
  • Start by defining the underlying interface pathBASE_URL
  • encapsulationrequestReturns a value withPromiseThe packagewx.requestmethods
  • It’s expanded laterPromiseThe instancefinallyMethods. The reason is that the phone will not reportfinallyThis method is wrong.
  • Finally, the interface is exported, and this example exports onepostRequested by way oftestMethods.

The test interface./pages/index/index.js only lists the relevant code

// Import the interface
import { test } from '.. /.. /api/api';

Page({
  data: {...res_data: null.// Define data. },...onLoad() {
    test({
      title: "post-test"
    }).then(res= >{
      this.setData({
        res_data: JSON.stringify(res) }); })},... })Copy the code

Display interface data./pages/index/index.wxml

<view class="container">
  {{api_test}}
</view>
Copy the code

Json structure obtained after calling the interface

{
  "code":200."data": {"title":"post-test"."message":"wechat applet api test post"
  },
  "msg":"success"
}
Copy the code
  • thisjsonStructure is composed ofkoa2Write a simple example to provide.

koa2The relevant code

const Router = require('koa-router');
const router = new Router();

router.post('/test'.async (ctx,next) => {
  const { title } = ctx.request.body;
  ctx.body = {
    code: 200.data: {title: title || "default".message: "wechat applet api test post"
    },
    msg: "success"
  };
});

router.use('/api/v2', router.routes());
module.exports = router;
Copy the code
  • For simplicity, write the result directly into the route.