express+ mockjs 搭建mock服务器

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. 跨域问题:
    1> 跨域问题只需要在 app.all 入口中配置:
     res.header("Access-Control-Allow-Origin",":*")
    
    2> 但是会报错:
    在这里插入图片描述
    3> 然后找方法:
    res.header('Access-Control-Allow-Credentials', true);
    
    报错还是一样的
    4> 后来看了这篇文章:
    http://www.it1352.com/1086516.html
    然后将 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));

医者医人医世难自医。请各位指教。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值