Make writing a habit together! This is the 10th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

preface

In day 9, we integrated tabBar to implement the main four page switching effects of the applets entry, and today we started to develop a common Request utility class for interface interworking. The last article was about using the Apifox tool to wrap mock for front-end development, but using the Apifox tool is a bit cumbersome. Let’s go straight to the back-end Demo interface we’ve already written.

Demand analysis

As the title says, what we are going to implement today is that the project can access the interface of the distributed platform. Let me explain why I want to do this first.

  • Distributed deployment of interfaces Our back-end interface may be distributed, for example, we start with only one server, but later find that it has limited computing power or needs to use multiple servers to load balance traffic. At this point, we simply deploy multiple copies of the same service and use Nginx for load balancing. In this case, we can just say that a service (for example, a user-specific service) is processed on a single server. This article focuses on how to solve this situation
  • In fact, if using the microservice engine development, we docking and the common front and back end separation project is the same, because the microservice project has a gateway, based on the gateway can be distributed to different serve
  • Here I take Alipay as an example. It has taobao, Ele. me and other businesses. If I want to start a new moving business line, give him a name ant move, I opened a new entrance on Taobao, based on the server render to achieve all my business, on the bottom of the tabBar as a flow entrance for access. At this time, we need to support three lines of service: Taobao, hungry me, ants move. We can also do the first case

Implement multi-environment development

Before we implement different interface access, we first need to implement the configuration of development and production multi-environment (it is impossible for us to interface docking in production environment). We modify our dev.js and prod.js under the project config, and add our interface configuration in env configuration, as follows

  env: {
    NODE_ENV: '"production"',
    HOME_REQ_URL: '"http://localhost:4001/one"',
    CATEGORY_REQ_URL: '"http://localhost:4001/one"',
    SHOP_CART_REQ_URL: '"http://localhost:4010/ten"',
    USER_REQ_URL: '"http://localhost:4010/ten"',
  },
Copy the code

We’ve divided the four entries into two back-end interfaces

IP address of the home page and category page: entrance 401/one

Shopping cart and personal center corresponding IP :4010/ten entrance

The specific code can be downloaded from my Gitee:Gitee.com/liangminghu…

Pay attention toThe two corresponding configuration files must be addedAfter we modify the configuration, let’s verify it

We modify home’s index.tsx code as follows

import { Component } from "react"; import { View, Text } from "@tarojs/components"; import "./index.scss"; export default class Home extends Component { componentWillMount() {} componentDidMount() {} componentWillUnmount() {} componentDidShow() { console.log(process.env.HOME_REQ_URL); } componentDidHide() {render() {return (<View className="home"> </View> </View>); }}Copy the code

Notice that we changed the name of the class and the className of the view to Home and Home to prevent the styles from colliding, Num run dev:weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap :weap

Write a generic Request wrapper class

Create a new utils/request folder under SRC and create a new index.ts file with the following contents

import Taro from "@tarojs/taro"; function request(url, data, method): Promise<any> { return Taro.request({ url, data, header: { "content-type": "application/json", }, timeout: 10000, method: method, dataType: "json", success: Function (res) {//todo codec handles return promise.resolve (res.data); }, fail: function (err) {//todo exception handling console.log(err); }}); } function get(url) { return request(url, null, "GET"); } function post(url, data) { return request(url, data, "POST"); } function del(url) { return request(url, null, "DELETE"); } function put(url, data) { return request(url, data, "POST"); } export { get, post, del, put };Copy the code

Encapsulate the respective request methods

Let’s create a new API folder under utils and create the following folders and their index.ts files

The contents of index.ts corresponding to home are as follows

import { get, post, put, del } from ".. /.. /request"; const homeReqUrl = `${process.env.HOME_REQ_URL}/index`; export const testGet = () => get(homeReqUrl); export const testPost = (data) => post(homeReqUrl, data); export const testPut = (data) => put(homeReqUrl, data); export const testDel = (id) => del(`${homeReqUrl}/${id}`);Copy the code

Let’s try the home page call interface

Modify page/home/index.ts to the following content

import { Component } from "react"; import { View, Text } from "@tarojs/components"; import { testGet, testPost, testDel, testPut } from ".. /.. /utils/api/hmoe"; import "./index.scss"; export default class Home extends Component { componentWillMount() {} componentDidMount() {} componentWillUnmount() {} componentDidShow() { testGet().then((res) => { console.log(res); }); testPost(null).then((res) => { console.log(res); }); testDel('123123').then((res) => { console.log(res); }); testPut(null).then((res) => { console.log(res); }); } componentDidHide() {render() {return (<View className="home"> </View> </View>); }}Copy the code

We can see the following output in the console

You need to open this configuration of wechat developer tools before you start calling the interface, otherwise the local domain name cannot be accessed

Modify the API paths and corresponding index.ts of other entries

Here we just need to change the API base directory and the index.ts class name and style name under the pages/ corresponding entry. You can visit my gitee to see what is changed :gitee.com/liangminghu…

The final validation

We end up with 4001-related output from the console corresponding to the home page and category, and 4010 output from the console corresponding to 4010

conclusion

In this article, we have completed the realization of accessing different business platforms for the same project. If you have unclear codes or have not achieved the final effect, you can compare my codes. In the next article, I am going to deal with exception codes and implement login Settings and user information