- 安装
npm i body-parser express mockjs -D
** 说明
body-parser : 处理post请求数据的
express nodeJs框架
mockjs 模拟数据的 //暂时没有用到
- 书写nodeJs逻辑
// 路径 mock/index.js
var express = require("express"); //引入express模块
var Mock = require("mockjs"); //引入mock模块
var fs = require("fs");
var app = express(); //实例化express
var bodyParser = require("body-parser");
//创建application/json解析
var jsonParser = bodyParser.json();
/*为app添加中间件处理跨域请求*/
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type");
next();
});
// 设置get请求
app.get("/index", function (req, res) {
res.send("sdf")
})
// 设置接口
app.post("/login", jsonParser, function(req, res){
var userName = req.body.user;
var password = req.body.password;
console.log("User name = "+userName+", password is "+password);
var data=[
{
data:213,
num:444,
age:12
},
{
data:456,
num:678,
age:13
}];
if (userName && password) {
res.status(200),
res.json(data)
}else {
res.send("no");
}
});
/**
* 监听8090端口
*/
app.listen("8090");
运行 : node mock
- vuex封装
// store.js
import ajax from "axios";
export default {
actions: {
mocks({ commit } ,param) {
return new Promise( (res, req) => {
ajax.post('/login', param)
.then(function (response) {
res(response)
})
.catch(function (error) {
req(error)
});
})
}
}
}
4.调用
import { mapActions } from "vuex";
export default {
created() {
let param = {
user: 'Fred',
password: 'Flintstone'
}
this.mocks(param).then(res => {
console.log(res);
})
},
methods: {
...mapActions(["mocks"]),
}
}