express + mockjs 搭建mock服务器
安装
// 安装express mockjs
npm install express mockjs -D
//安装热更新 supervisor
npm install supervisor
构建服务
// 源码
const express = require("express")
const app = express();
const Mock = require("mockjs")
const cors = require('cors');
const whitelist = ['http://localhost:8080'];
const corsOptions = {
credentials: true, // This is important.
origin: (origin, callback) => {
if (whitelist.includes(origin))
return callback(null, true)
callback(new Error('Not allowed by CORS'));
}
}
app.use(cors(corsOptions));
app.all('/api/*', function (req, res, next) {
res.header("Access-Control-Allow-Headers", "X-Requested-With, mytoken")
res.header("Access-Control-Allow-Headers", "X-Requested-With, Authorization")
res.setHeader('Content-Type', 'application/json;charset=utf-8')
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1')
if (req.method == "OPTIONS") res.send(200);/*让options请求快速返回*/
else next()
});
app.get("/api/user/getUserRelationPages/:id", (req, res) => {
let data = Mock.mock({
code: 200,
data: {
current: 1,
pages: 10,
total: 10,
searchCount: true,
size: 0,
"records|10": [
{
"createTime": "@datetime('yy-MM-dd HH:mm:ss')",
"description": "@cparagraph",
"headUrl": "http://xiaoyue.work/my-logo.jpeg",
"id": "@id",
"imId": "2e6b5370-ef18-11e9-80c3-f5f1908528bc",
"imName": "481131946620191015145114522",
"nickName": "@cname",
"phoneNumber": "13575758097",
"pyName": "@first",
"pyRemark": "pyRemark",
"remark": "@cname",
"sex|1": ["男", "女"],
"userName": "@csentence(3,5)"
}
]
},
msg: ""
})
res.send(data)
})
/**
* 获取个人动态
*/
app.get("/api/trends/getTrendsPages", (req, res) => {
let data = Mock.mock({
"code": 200,
"data": {
"current": 1,
"pages": 1,
"records|10": [
{
"cId": "@id",
"content": "@csentence",
"createBy": 1,
"createTime": "@datetime('yy-MM-dd HH:mm:ss')",
"externalLink": "",
"id": "@id",
"imageUrls": "http://xiaoyue.work/my-logo.jpeg",
"likeNum": "@increment",
"likeuids": "12,13,14,15",
"updateBy": 1,
"updateTime": "@datetime('yy-MM-dd HH:mm:ss')",
"videoUrl": ""
}
],
"searchCount": true,
"size": 10,
"total": 10
},
"msg": ""
})
res.send(data)
})
app.get("/api/user/getUserDetailInfo/:id",(req,res)=>{
let data =Mock.mock({
"code": 200,
"data": {
"description": "@csentence",
"follow|1": [true,false],
"headUrl": "http://xiaoyue.work/my-logo.jpeg",
"id": "@id",
"imId": "string",
"imName": "string",
"launchId": 0,
"nickName": "@cname",
"phoneNumber": "13575758097",
"pyName": "@first",
"sex|1": ['男',"女"],
"userName": "@cname"
},
"msg": "string"
})
res.send(data)
});
app.listen("9090", (err) => {
if (!err) {
console.log("Mock server is running!")
}
})
填坑过程:
- 跨域问题:
1> 跨域问题只需要在 app.all 入口中配置:
2> 但是会报错:res.header("Access-Control-Allow-Origin",":*")
3> 然后找方法:res.header('Access-Control-Allow-Credentials', true);
4> 后来看了这篇文章:
然后将 1> 、 3> 中的方法删掉,重新写:
// 安装cors
npm install cors
// 源码:
const cors = require('cors');
const whitelist = ['http://localhost:4200', 'http://example2.com'];
const corsOptions = {
credentials: true, // This is important.
origin: (origin, callback) => {
if(whitelist.includes(origin))
return callback(null, true)
callback(new Error('Not allowed by CORS'));
}
}
app.use(cors(corsOptions));
医者医人医世难自医。请各位指教。