Mock data is used in vue projects. Data and project are coupled together, which is not elegant. As a front-end, how can you tolerate this method? In this particular article, I will document how to use KOA2 to build the server and provide mock data.

Initialize the VUE project

This will be a vUE project, but other types of projects can still use this mock data approach.

vue create vue-koa2-demo
Copy the code

The premise is to install vuE-CLI scaffolding, my computer is installed vuE-CLI3 version. After following the instructions step by step, remember to install VUEX for subsequent use and start the project.

The KOA2 project is initialized

After the front end project is ready, start the KOA installation

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

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

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 cors to request await cors() across domains; Body = json. parse(fs.readfilesync (fs.readfilesync))'./static/data.json')); }) app.use(router.routes()).use(router.allowedmethods ());let port=3000;
app.listen(port,()=>{
  console.log('server is running on'+port)
})

Copy the code

A data.json is requested above. Create the static folder in the root directory of the project and create data.json

[{
  "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"."age": "28"
}]
Copy the code

Execute the command in the terminal to start the KOA project

node server.js
Copy the code

When you see the following figure, the project is successfully started

Retrofitting front end project

  • Modify the home. vue file
<template>
  <div class="home">
    <ul>
      <li v-for="item in list" :key="item.id". > < p > 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 the code
  • Modify the app. vue file
<template>
  <div id="app">
    <router-view />
  </div>
</template>
Copy the code
  • Modify the 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 the code

Remember to install AXIOS ahead of time, where you need to use AXIOS to request the back-end interface.

  • Create a configuration file. Create a vue.config.js file in the root directory.
Module. exports = {devServer: {port: 8085, // port number HTTPS:false, // https:{type:Boolean}
    open: true// Configure automatic start browser proxy: {"/api": {
        target: "http://127.0.0.1:3000",
        changeOrigin: true,
        pathRewrite: {
          "^/api": "/"}}}}};Copy the code

Restart the project

npm run serve
Copy the code

You should see the JSON data defined in the KOA-Demo project displayed on the page, and you’re done.

This allows you to separate the mock data project from the concrete front-end project for easier use later. No more begging the back end for mock data, do it yourself!

The resources

  • Koa website