“This is the fifth day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

preface

Through the sharing of the previous few articles, we have implemented the bottom navigation bar, the head search bar and the TAB TAB of our web version of the Gold nuggets app. But so far there is no interaction with the back end. Today we will start with the front and back end, analyzing the official API, implementing our own back end API, and displaying the data obtained through the front end. In the last article, our tabs were written to death, but now we’re going to use a back-end API to get real classified data for real dynamic data binding. The functions to be realized in this sharing are:

  • Axios secondary encapsulation
  • Nodejs + KOA is used to encapsulate the back-end interface
  • Dynamic TAB page binding

Axios secondary encapsulation

You probably know that AXIos is an Ajax asynchronous request library wrapped with Promise that you can use directly, but why do we need to wrap it twice? This is because if we directly use axios, axios all use the default configuration, that is to say, all interface request use the same set of configuration, if we want to only a few interface separately configuration are bad to did, if directly modify axios configuration will affect all the configuration of the interface, this is obviously unreasonable, So we’re going to do a secondary wrapper of AXIOS and configure different interfaces differently by creating different INSTANCES of AXIOS. Specific implementation ideas are as follows:

  • Add an API directory under SRC
  • Add http.js and juejinapi.js respectively under the new API. Http.js is used for secondary encapsulation of AXIOS, and juejinapi.js is used to encapsulate the interface of the request backend
  • Import AXIos in http.js and create an instance of AXIos
  • Set up AXIOS response interception and request interception

The complete code is as follows:

import axios from 'axios'
// Create a new axios instance
let http = axios.create({
    baseURL: '/api'./ / set the baseURL
    headers: { // Set the header information
        "Content-Type": 'application/json; charset=UTF-8'}});// Set response interception
http.interceptors.response.use(response= > {
    return response.data;
})


// Set request interception
http.interceptors.request.use(config= > {
    return config;
})

export default http;
Copy the code

Setting up back-end services

Since we have to request the official API interface to get the data, but if we request directly in the front-end project, we will report 500 server error, but the same axios on the back-end request is ok, so we have to build another back-end service. Nodejs and KOA can be used to build a backend service. Nodejs and KOA can be used to build a backend service. Nodejs and KOA can be used to build backend services. Here is just a little bit of a wrapper on how the back end requests the official Nuggets API. You can refer to the following steps to modify the code:

  • Add juejin. Js to ruoters directory
  • Import the AXIOS and KOA-Router libraries in this file
  • Then define a ‘/category’ route and request the official interface to get the label type in that route via AXIOS: api.juejin.cn/tag_api/v1/…
  • In the end, juejin sub-routes are integrated into the main routes in the Index. Js of the Routers directory for unified management

The specific code is as follows:

// routers/juejin.js
const {
    default: axios
} = require('axios');
const Router = require('koa-router')
const HttpCode = require('.. /utils/HttpCode')
const router = new Router();

router.get('/category'.async (ctx, next) => {
    console.log('aaa');
    const {
        data
    } = await axios.get('https://api.juejin.cn/tag_api/v1/query_category_briefs?aid=2608&uuid=7050641888232212007');
    ctx.body = {
        code: HttpCode.Success.success_ok,
        msg: HttpCode.Success.success_ok_msg,
        data
    }
    next()
})

module.exports = router;
Copy the code

Integrate juejin child routes into the main route

// routers/index.js
// ...
router.use('/juejin', juejin.routes(), juejin.allowedMethods())
Copy the code

TAB dynamically obtains and binds TAB pages

Having rewrapped AXIos above, we can now request the back-end interface directly to get the actual label type data.

  • Request interface definition

    • Add the juejinapi.js file under SRC/API
    • In this file, start by importing axios, which we wrapped above
    • Define a queryCategoryBriefs method in which you make a GET request directly to the back end via AXIOS

    The implementation code is as follows:

    import http from "./http";
    export default {
        queryCategoryBriefs: function () {
            return http.get('/juejin/category')}}Copy the code
  • Modify home. vue to dynamically fetch label data

    • Import the queryCategoryBriefs method we just wrapped in home.vue
    • Call this method and assign the returned result to the reactive variable categoryList
    • Since the official result is an object containing many attributes, and the name of the label is in the category_name attribute, Therefore, you need to change the key and title values in the van-tab TAB of the template to item.category_id and item.category_name respectively

    The key codes are as follows:

    <! --Home.vue-->
     <van-tab
        v-for="item in categoryList"
        :key="item.category_id"
        :title="item.category_name"
      >
        <div class="tab-list-content">{{item.category_name}} list</div>
      </van-tab>
    Copy the code
    // ...
    import api from ".. /api/juejinapi";
    // ...
    
    setup() {
        const state = reactive({ active: 1.categoryList: []}); api .queryCategoryBriefs() .then((res) = > {
            console.log(res.data.data);
            state.categoryList = res.data.data;
          })
          .catch((err) = > {
            console.log(err);
          });
    
        return {
          ...toRefs(state),
          image,
    };
    Copy the code

conclusion

Well through the above simple steps to achieve dynamic data acquisition and binding, the effect picture is as follows, although on the surface with the previous chapter in the same, but in fact this time the data is dynamic acquisition and binding oh. The result of this share is no different from the last one, but we did a lot of work behind the scenes, such as the encapsulation of the back-end service interface, the secondary encapsulation of the AXIOS asynchronous request library, and the dynamic binding of tag data. Okay, guys, that’s all for this share. Next time I will share with you click the search box to jump to the new page and implement the check-in function.