Building mock data environment with vue+koa2

Keywords: Vue JSON axios npm

I wrote an article a while ago Implementation of mock data mode in front-end vue project In this paper, we mainly use mock data in vue project. The data and project are coupled together, which is not elegant. As a front-end with pursuit, how can we tolerate this method? In this article, we record the method of using koa2 to build the server and provide mock data.

Initialize vue project

Here, vue is the main project. Of course, other types of projects can still use this kind of mock data.

vue create vue-koa2-demo
 Copy code

The premise is that the scaffold of Vue cli is installed, and the version of Vue cli 3 is installed in my computer. After step-by-step selection according to the requirements, remember to choose to install vuex, use it later and start the project.

koa2 project initialization

After the front end project is completed, start to install koa

mkdir koa-demo
cd koa-demo
npm koa koa-router koa-cors
Copy code

After the installation, create a new server.js in the root directory of the project

let Koa=require('koa')
let Router=require('koa-router')
let cors=require('koa-cors')
let fs=require('fs')

const app=new Koa()
const router=new Router()

router.get('/getData',async ctx=>{
  // Allow cross domain requests from cors
  await cors();
  // Return data
  ctx.body=JSON.parse(fs.readFileSync('./static/data.json'));
})

// Connecting koa and Middleware
app.use(router.routes()).use(router.allowedMethods());

let port=3000;
app.listen(port,()=>{
  console.log('server is running on'+port)
})

Copy code

A data. JSON was requested above. You need to create a new folder static and data.json in the root directory of the project

[{
  "id": 1,
  "name": "Cao Cao",
  "age": "18"
}, {
  "id": 2,
  "name": "Sun Quan",
  "age": "20"
}, {
  "id": 3,
  "name": "Liu Bei",
  "age": "24"
}, {
  "id": 4,
  "name": "Wei Yan",
  "age": "28"
}]
Copy code

Executing command in terminal to start koa project

node server.js
 Copy code

When you see the figure below, it indicates that the project is started successfully

Transformation front end project

  • Modify the Home.vue file
<template>
  <div class="home">
    <ul>
      <li v-for="item in list" :key="item.id">
        <p>full name:{{ item.name }}</p>
        <p>Age:{{ item.age }}</p>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "Home",
  computed: {
    list() {
      return this.$store.state.list;
    }
  },
  mounted() {
    this.getlist();
  },
  methods: {
    getlist() {
      this.$store.dispatch('getData')
    }
  }
};
</script>


Copy code
  • Modify App.vue file
<template>
  <div id="app">
    <router-view />
  </div>
</template>
Copy code
  • Modify store/index.js
import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    list: []
  },
  mutations: {
    setlist(state, data) {
      state.list = data;
    }
  },
  actions: {
    getData({ commit }) {
      axios
        .get("/api/getData", {
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
          }
        })
        .then(res => {
          if (res.status === 200) {
            return res.data;
          }
        })
        .then(res => {
          commit("setlist", Array.from(res));
        });
    }
  },
  modules: {}
});

Copy code

Remember to install axios in advance. You need to use axios to request the backend interface.

  • New profile
    Create a new vue.config.js in the root directory. Because the front and back end projects are cross domain, you need to use a proxy implementation.
module.exports = {
  devServer: {
    port: 8085, // Port number
    https: false, // https:{type:Boolean}
    open: true, //Configure autostart browser
    proxy: {
      "/api": {
        target: "http://127.0.0.1:3000",
        changeOrigin: true,
        pathRewrite: {
          "^/api": "/"
        }
      }
    }
  }
};
Copy code

Restart project

npm run serve
 Copy code

You will see that the json data defined in the koa demo project is displayed on the page, and it is finished.

In this way, the project of mock data can be separated from the specific front-end project, which is more convenient to use. Don't ask the back end to give mock data anymore. Do it yourself!

reference material

Posted by cschotch on Sun, 17 May 2020 17:26:47 -0700