Detailed explanation of using vue, koa2, and mockjs to simulate data
This article mainly introduces you to the relevant information about using vue + koa2 + mockjs to simulate data. The article introduces it in detail through the example code. It has certain reference learning value for everyone's study or work. Friends who need it can follow it below. Come and learn with me.
About mockjs, the official website describes it as
1. Separation of front-end and back-end
2. You can intercept Ajax requests and return simulated response data without modifying the existing code. .
3. Rich data types
4. Simulate various scenarios through random data.
And so on.
The first step is to install the vue-cli project. There is not much to say on the Internet.
Friends who need it can refer to this article: http://www.jb51.net/article /118987.htm, the introduction is very detailed.
The second step is because the local vue accesses the local mock
1. Configure the vue proxy
The proxyTable in config/index.js, because the local node The started service accesses port 3000 by default
So configure http://localhost:3000/
proxyTable: { '/api': { target: 'http://localhost:3000/', changeOrigin: true, pathRewrite: { '^/api': '/' } }
2 in the target in mianjs of the vue project
import axios from 'axios' axios.defaults.baseURL = '/api'
The third step is to build the nodejs koa2 project
Install koa globally, not koa2. Note
1. npm install -g koa-generator
Create a folder under which HelloKoa2 is your project name
2, koa2 HelloKoa2
Enter the folder and execute the installation dependencies
3. cd HelloKoa2 and then npm install
The above completes the initialization of nodejs and then operates
4. Continue to install dependency files
npm install mockjs --save -dev //mock文件 npm install koa2-cors --save -dev //node端配置cors支持跨域用
5. Configure the app.js file. Note that the new part in the comments below is the new thing added to the original app.js file.
const Koa = require('koa') const app = new Koa() const views = require('koa-views') const json = require('koa-json') const onerror = require('koa-onerror') const bodyparser = require('koa-bodyparser') const logger = require('koa-logger') const cors = require('koa2-cors') // 新增部分处理跨域 //这里提一点题外话 假如routes文件新增一个路径就的在下面增加路劲 //假设routes新增一个user.js //新增一个user需要修改两个地方这里是一个 下面还有一个地方 //这里需要 const user = require('./routes/user') const index = require('./routes/index') const users = require('./routes/users') // error handler onerror(app) // middlewares app.use(bodyparser({ enableTypes:['json', 'form', 'text'] })) app.use(cors()) // 新增部分处理跨域 app.use(json()) app.use(logger()) app.use(require('koa-static')(__dirname + '/public')) app.use(views(__dirname + '/views', { extension: 'pug' })) // logger app.use(async (ctx, next) => { const start = new Date() await next() const ms = new Date() - start console.log(`${ctx.method} ${ctx.url} - ${ms}ms`) }) //这里提一点题外话 假如routes文件新增一个路径就的在下面增加路劲 //假设routes新增一个user.js //这里需要 app.use(user.routes(), user.allowedMethods()) app.use(index.routes(), index.allowedMethods()) app.use(users.routes(), users.allowedMethods()) // error-handling app.on('error', (err, ctx) => { console.error('server error', err, ctx) }); module.exports = app
6. Officially use mock me Use it directly in routes/index.js
The routes/index.js file is as follows
const router = require('koa-router')() var Mock = require('mockjs') //引入mockjs const Random = Mock.Random; //引入mockjs生成随机属性的函数 random具体可以生成 //哪些东西详见http://mockjs.com/examples.html router.prefix('/index') router.get('/string', async (ctx, next) => { //116到125 是mock的第一种使用方法,这种方法随机生成1到10个数组但是每个数组的author、title等都一样 // ctx.body = await Mock.mock({ // // 属性 list 的值是一个数组,其中含有 1 到 10 个元素 // 'arr|1-10': [{ // // 属性 id 是一个自增数,起始值为 1,每次增 1 // 'id|+1': 1, // 'author|+1': Random.cname(), // 'img': Random.image('100x100'), // 'title':Random.csentence(5, 9) // }] // }) //127到141是mock的第二种方法主要使用Random函数来生成 这里生成的title、author等每个都不一样 const produceNewsData = function() { let articles = []; for (let i = 0; i < 50; i++) { let newArticleObject = { title: Random.csentence(5, 30), // Random.csentence( min, max ) author: Random.cname(), // Random.cname() 随机生成一个常见的中文姓名 } articles.push(newArticleObject) } return { articles: articles } } ctx.body = await produceNewsData() })
Here is a little mention http://mockjs.com/examples.html Official website to see each data clearly Usage
7. Start node
npm run dev
Related recommendations:
php simulates the effects of common database operations
Use MySQL logs to simulate data change trajectories
php simulates the effects of common database operations
The above is the detailed content of Detailed explanation of using vue, koa2, and mockjs to simulate data. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
