Writing in the front

The main purpose of this article is to learn how to use the KOA framework to build Web services that provide some back-end interfaces for the front end to invoke. The purpose of setting up this environment is that before the interface is agreed with the background engineer, the functions related to the back-end data request can go through the HTTP path set up by the front-end engineer, instead of directly writing several dead data in the front end. That is, simulate the back-end interface.

Of course, in this whole process (setting up the environment + developing the sample demo), the following points are involved. Include:

  • KoA2
  • Node knowledge
  • Cross-domain problem
  • The use of the fetch
  • Promise of the involved
  • Vuex -> the use of state, mutations, actions

Part one: Setting up the environment

Vue + VUEX environment

The first is the vUE + VUe-Router + VUex environment. We use vuE-CLI scaffolding generation projects. Those of you who know vUE will be familiar with this.

Vue --version // Build project vue init webpack project name // Test whether the vue project runs successfully NPM run devCopy the code

Since the scaffold generated VUE project does not contain vuEX, install the VUex.

// Install vuex NPM I vuex --saveCopy the code

Koa2 environment

With the front-end project built, we started building our back-end services.

Start by creating a new directory in your development tools (whether WebStorm or Sublime) to build koA-based Web services.

In this case, we might as well call this directory KOA-demo.

Then execute:

// Go to the directory CD koa-demo // generate package.json NPM init -y // install the following dependencies NPM I koa NPM I koa-router NPM I koa-corsCopy the code

With the KOA and two middleware installed, the environment is complete.

Part two: Sample development

The environment is built to be used, so let’s write a demo right away. Demo development is both an exercise in how to write code in the development environment and, in turn, a validation of how well the environment works.

Back-end interface development

In this case, the backend provides only one service, which is an interface for the front-end to return JSON data. The code contains comments, so go directly to the code.

Server. The js file

// server.js file 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 ('/getJson', async CTX => {// Back end allows cors to cross domain request await cors(); Parse (fs.readfilesync ('./static/material. JSON ')); }); App.use (router.routes()).use(router.allowedmethods ()); App.listen (3000);Copy the code

This uses a JSON file in the ‘./static/material. Json ‘path. The code for this json file is:

/ / material. Json file [{" id ": 1," date ":" 2016-05-02 ", "name" : "zhang", "address" : "Beijing's tsinghua university,"}, {" id ": 2," date ": "2016-05-04", "name" : "bill", "address" : "Shanghai's fudan university,"}, {" id ": 3," date ":" 2016-05-01 ", "name" : "detective", "address" : "Guangdong zhongshan university,"}, {" id ": 4," date ":" 2016-05-03 ", "name" : "Daisy", "address" : "university", shenzhen city, guangdong province,}, {" id ": 5," date ": "2016-05-05", "name" : "han meimei", "address" : "sichuan university, sichuan,"}, {" id ": 6," date ":" 2016-05-11 ", "name" : "Liu Xiaolv", "address" : "Central south university, hunan province,"}, {" id ": 7," date ":" 2016-04-13 ", "name" : "once temple", "address" : "university of nanjing, jiangsu province,"}]Copy the code

We then start the service with the following command

node server.jsCopy the code

Test whether the interface is good

Open a browser, type http://127.0.0.1:3000/getJson. See if the JSON data from the JSON file is displayed on the page. If it is, we have set up the service that provides the JSON data.

Example of a front-end calling a back-end interface

To highlight the focus, eliminate interference, easy to understand. Our front end will write a component that has two parts: a button that calls the getJson interface of the Web service; Then there is a content display area where you take the data returned from the back end and display it in this area of the component.

Let’s look at the component file first

<template> <div class="test"> <button type="button" @click="getJson" class="showJson">{{json}}</div> </div> </template> <script> import {store} from '.. /vuex' export default { computed: { json(){ return store.state.json; } }, methods: { getJson(){ store.dispatch("getJson"); } } } </script> <style scoped> .showJson{ width:500px; margin:10px auto; min-height:500px; background-color: palegreen; } </style>Copy the code

It’s very simple. I won’t explain it much. Then look at our vuex file.

import Vue from 'vue' import Vuex from 'vuex'; Vue.use(Vuex) const state = { json: [], }; const mutations = { setJson(state, db){ state.json = db; }} const actions = {getJson (context) {/ / call our back-end getJson interface fetch (' http://127.0.0.1:3000/json '{method: 'GET', // mode:'cors', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, }).then(function (res) { if(res.status === 200){ return res.json() } }).then(function (json) { //console.log(typeof Array.from(json), Array.from(json)); context.commit('setJson', Array.from(json)); })}}; export const store = new Vuex.Store({ state: state, mutations: mutations, actions: actions, })Copy the code

Ok, we’re done with the code, before we get the back-end data.

This is what happens when you get the back-end data.

Programming in practice, hurry to try it!

Afterword.

Vue scaffold-based projects, analog asynchronous data, you can also directly in the scaffolding generated static folder placed data, pretend to be the background to take over the data.

But building a Web service based on Express or KOA is something a front-end engineer should know.

OK, that’s it. If this article has taught you anything, I’m glad. Welcome to like, in order to help more students!

About the author

Technology blog | | making | | Denver home page