Detailed description of vue + vuex + koa2 Development Environment establishment and example development, vuexkoa2

Source: Internet
Author: User
Tags node server

Detailed description of vue + vuex + koa2 Development Environment establishment and example development, vuexkoa2

Preface

The main purpose of this article is to learn how to use the koa framework to build web services and provide some backend interfaces for frontend calls.

The purpose of setting up this environment is that the front-end engineer can request data from the back-end engineer through the http path set up by the front-end engineer before agreeing with the back-end engineer on the Interface but not connecting the interface, instead of writing dead data directly at the front end. That is, simulate the backend interface.

Of course, the following knowledge points are involved in the entire process (build the Environment + demo of the development example.

Including:

  1. Knowledge points of koa2
  2. Node knowledge point
  3. Cross-origin problems
  4. Use of fetch
  5. Use of axios
  6. Promise
  7. Vuex-> usage of state, mutations, and actions

Part 1: Environment Construction

Vue + vuex Environment

The first is the vue + vue-router + vuex environment. We use vue-cli scaffolding to generate a project, and we should be familiar with this project.

// Globally install the scaffold tool npm I vue-vli-g // verify whether the scaffold tool is successfully installed vue -- version // build the project vue init webpack project name // test whether the vue project is running successful npm run dev

Because the vue project generated by scaffolding does not contain vuex, install vuex again.

// Install vuexnpm I vuex -- save

Koa2 Environment

After the frontend project is built, we will start to build our backend services.

First, create a directory in your development tool (webstorm or sublime) to build a koa-based web service.

Here, we may name this directory koa-demo.

Then execute:

// Enter the directory cd koa-demo // generate package. jsonnpm init-y // install the following dependency npm I koanpm I koa-routernpm I koa-cors

After koa and two middleware are installed, the environment is complete.

Part 2: Sample Development

The environment was set up for use, so we immediately wrote a demo.

Demo development is not only a process of practicing how to write code in the development environment, but also a process of verifying whether the environment is set up correctly or not.

Backend interface development

In this example, the backend provides only one service, that is, an interface for the front-end to return json data. The Code contains comments, so you can directly add the code.

Server. js File

// Server. js file let Koa = require ('koa'); let Router = require ('koa-router '); let cors = require ('koa-cors '); // introduce the modejs File System APIlet fs = require ('fs'); const app = new Koa (); const router = new Router (); // provides a/getJson interface router. get ('/getjson', async ctx =>{// the backend allows cors cross-origin requests await cors (); // return the data ctx to the front end. body = JSON. parse (fs. readFileSync ('. /static/material. json ');}); // connect koa to the two middleware apps. use (router. routes ()). use (router. allowedMethods (); // listens to port 3000 of the app. listen (0, 3000 );

Here, a json file is used in the './static/material. json' path. The code of this json file is:

// Material. json file [{"id": 1, "date": "2016-05-02", "name": "Zhang San", "address": "Beijing Tsinghua University ",}, {"id": 2, "date": "2016-05-04", "name": "Li Si", "address": "Shanghai Fudan University" ,}, {"id ": 3, "date": "2016-05-01", "name": "Wang Wu", "address": "Guangdong Sun Yat-sen University" ,},{ "id": 4, "date": "2016-05-03", "name": "Zhao six", "address": "Guangdong Shenzhen University", },{ "id": 5, "date ": "", "name": "Han Meimei", "address": "Sichuan University", },{ "id": 6, "date ", "name": "Liu Xiaolu", "address": "Hunan Central South University", },{ "id": 7, "date": "2016-04-13", "name ": "Zeng tan", "address": "Nanjing University, Jiangsu Province",}]

Run the following command to start the service:

node server.js

Test whether the interface is good

Open the browser and enter http: // 127.0.0.1: 3000/getJson. Check whether the json data in the json file is displayed on the page. If it can be displayed, it indicates that this service provides json data, which has been set up.

Example of frontend interface call

To highlight the key points and eliminate interference, it is easy to understand. The front-end writes a component. The component has two parts: a button to call the getJson interface of the web service, and a content display area. After obtaining the data returned by the backend, display it in the component area.

First, let's look at the component file.

<Template> <div class = "test"> <button type = "button" @ click = "getJson"> retrieve json from backend </button> <div class = "showJson" >{{ json }}</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>

It is very simple and I will not explain it much.

Then read 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 backend getJson interface fetch ('HTTP: // 127.0.0.1: 3000/json', {method: 'get', // mode: 'cors ', headers: {'access': '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 ,})

OK. The code is finished.

Axios

To change the fetch of this demo to the axios method, you need to do the following:

1. Install axios and reference axios in the vuex File

npm i axiosimport axios from 'axios'

2. Replace the partial fetch code:

const actions = { getJson(context){  axios.get('/json', {   method: 'GET',   // mode:'cors',   headers: {    'Accept': 'application/json',    'Content-Type': 'application/json',   },  }).then(function (res) {   if(res.status === 200){    return res.data   }  }).then(function (json) {   //console.log(typeof Array.from(json), Array.from(json));   context.commit('setJson', Array.from(json));  }) }};

3. Cross-origin is also encountered. modify it in webpack and add the proxyTable item configuration in the path config/index. js file:

proxyTable: {   '/json': {    target: 'http://127.0.0.1:3000',    changeOrigin: true,    pathRewrite: {     '^/json': '/json'    }   }  },

Postscript

A project built based on vue scaffolding can simulate asynchronous data acquisition. You can also directly place data in the static folder generated by scaffolding, and pretend to be the data obtained from the background.

However, building a web Service Based on express or koa should indeed be mastered by a front-end engineer.

OK. The above is the full text. I hope it will be helpful for everyone's learning, and I hope you can support the house of helping customers more.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.