标签:https filter vsc src turn delete error script ecif
如何在微信小程序使用mock.js实在是个问题,为了完全模拟访问路由和数据,选择在搭建本地mock服务器是一个不错的选择。
以下示例了一个mock服务器的搭建过程以及以学生为对象进行增删改查分页的示例。
安装了node.js
cnpm install express body-parser cors nodemon mockjs --save
(1)使用npm init -f
生成一个package.json
文件
? 修改为使用 nodemon 启动
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
(2)创建server.js文件,mock目录
server.js
中写入以下代码用于测试,在控制条输入npm start
启动服务器const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.get('/posts', (req, res) => {
res.send([
{
title: 'Hello World!',
description: 'Hi there! How are you?'
}
]);
});
// 指定端口
const PORT = 8081;
app.listen(PORT, () => {
console.log(`服务器启动,运行为http://localhost:${PORT}`);
});
控制台将会输出服务器启动,运行为http://localhost:8081
;我们在浏览器中访问http://localhost:8081/posts
,出现以下内容,那么说明服务器创建成功。
[
{
"title": "Hello World!",
"description": "Hi there! How are you?"
}
]
index.js
用于声明路由,一个student.js
,用来编写模拟学生对象相关操作代码。// student.js
const Mock = require('mockjs');
let list = [];
const count = 100;
for (let i = 0; i < count; i++) {
list.push(
Mock.mock({
id: '@increment',
stuNo: 20220000 + parseInt(`${i + 1}`),
stuName: '@cname',
stuGender: '@integer(0,1)',
stuPhone: /^1[0-9]{10}$/,
stuBirthday: '@date("yyyy-MM-dd")',
classNo: '@integer(201901,201912)'
})
);
}
// 增加学生
exports.add = (req, res) => {
const { classNo, stuBirthday, stuGender, stuName, stuPhone } = req.body;
list.push({
id: list[list.length - 1].id + 1,
stuNo: list[list.length - 1].stuNo + 1,
classNo: classNo,
stuBirthday: stuBirthday,
stuGender: stuGender,
stuName: stuName,
stuPhone: stuPhone
});
let msg = {
code: 20000,
data: {
listNum: list.length,
message: '添加成功!'
}
};
res.status(200).json(msg);
};
// 删除学生
exports.delete = (req, res) => {
const id = req.params.id;
// 判断id是否存在
let flag = list.some(item => {
if (item.id == id) {
return true;
}
});
if (flag) {
// id 存在
list = list.filter(item => item.id !== parseInt(id));
const msg = {
code: 20000,
data: {
listNum: list.length,
message: '删除成功!'
}
};
res.status(200).json(msg);
} else {
// id不存在
const msg = {
code: 40000,
data: {
msg: 'id不存在!'
}
};
res.status(500).json(msg);
}
};
// 更新学生信息
exports.update = (req, res) => {
const { id, classNo, stuBirthday, stuGender, stuName, stuPhone } = req.body;
// 判断id是否存在
let flag = list.some(item => {
if (item.id == id) {
return true;
}
});
if (flag) {
// id存在
list.some(item => {
if (item.id === id) {
item.classNo = classNo;
item.stuBirthday = stuBirthday;
item.stuGender = stuGender;
item.stuName = stuName;
item.stuPhone = stuPhone;
}
});
let msg = {
code: 20000,
data: {
message: '更新成功!'
}
};
res.status(200).json(msg);
} else {
// id不存在
const msg = {
code: 40000,
data: {
msg: 'id不存在!'
}
};
res.status(500).json(msg);
}
};
// 查询学生信息
exports.find = (req, res) => {
let { queryStr, page = 1, limit = 10 } = req.body;
// 根据学生姓名查询学生或者返回所有学生信息
const mockList = queryStr && queryStr.length > 0 ? list.filter(item => item.stuName.includes(queryStr)) : list;
// 数据分页
const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1));
let msg = {
code: 20000,
count: mockList.length,
data: pageList
};
res.status(200).json(msg);
};
// 根据id返回学生信息
exports.findById = (req, res) => {
const id = req.query.id;
const pageList = list.filter(item => item.id == id);
const msg = {
code: 20000,
data: pageList
};
res.status(200).json(msg);
};
// index.js
module.exports = function(app) {
const student = require('./student');
// 新增学生
app.post('/student/add', student.add);
// 删除学生
app.delete('/student/delete/:id', student.delete);
// 更新学生信息
app.put('/student/update', student.update);
// 查询学生信息
app.post('/student/list', student.find);
// 查询单个学生接口
app.get('/student', student.findById);
};
server.js
中引入index.js
文件,删除定义的posts接口const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
// 引入路由文件
require('./mock/index')(app);
// 指定端口
const PORT = 8081;
app.listen(PORT, () => {
console.log(`服务器启动,运行为http://localhost:${PORT}`);
});
以下为在小程序中编写的测试代码
<!--index.wxml-->
<view class="container">
<button catchtap='getStudent'>获取学生信息</button>
<button catchtap='deleteStudent'>删除学生信息</button>
<button catchtap='addStudent'>新增学生信息</button>
<button catchtap='updateStudent'>更新学生信息</button>
<button catchtap='findStudent'>查询单个学生</button>
</view>
//index.js
//获取应用实例
const app = getApp()
Page({
data: {},
getStudent:function(){
wx.request({
url: 'http://localhost:8081/student/list',
data:{
queryStr:'',
page:1,
limit:10
},
method: 'POST',
success: function (res) {
console.log('访问成功:', res);
},
fail: function (e) {
console.log('访问失败:', e);
},
complete: function () {
console.log('访问完成');
}
})
},
deleteStudent:function(){
wx.request({
url: 'http://localhost:8081/student/delete/1',
method: 'DELETE',
success: function (res) {
console.log('访问成功:', res);
},
fail: function (e) {
console.log('访问失败:', e);
},
complete: function () {
console.log('访问完成');
}
})
},
addStudent:function(){
wx.request({
url: 'http://localhost:8081/student/add',
data:{
classNo:'201901',
stuBirthday:'2019-05-31',
stuGender:0,
stuName:'李小珍',
stuPhone:'12345678910'
},
method: 'POST',
success: function (res) {
console.log('访问成功:', res);
},
fail: function (e) {
console.log('访问失败:', e);
},
complete: function () {
console.log('访问完成');
}
})
},
updateStudent:function(){
wx.request({
url: 'http://localhost:8081/student/update',
data: {
id:1,
classNo: '201901',
stuBirthday: '2019-05-31',
stuGender: 0,
stuName: '李小珍',
stuPhone: '12345678910'
},
method: 'PUT',
success: function (res) {
console.log('访问成功:', res);
},
fail: function (e) {
console.log('访问失败:', e);
},
complete: function () {
console.log('访问完成');
}
})
},
findStudent:function(){
wx.request({
url: 'http://localhost:8081/student?id=2',
data: {},
method: 'GET',
success: function (res) {
console.log('访问成功:', res);
},
fail: function (e) {
console.log('访问失败:', e);
},
complete: function () {
console.log('访问完成');
}
})
}
})
返回的结果如下:
3.新增学生信息
PS:因为前面id被删除了,所以这个时候更新会报错
2019/05/31 18:56
标签:https filter vsc src turn delete error script ecif
原文地址:https://www.cnblogs.com/yejingping/p/10956983.html