Giter Club home page Giter Club logo

mocker-api's Introduction

Mocker API LOGO

Buy me a coffee Build & Deploy Download Repo Dependents Open in unpkg Release npm version

中文 · Quick Start · Usage · Options · Delayed · Example · License · type

mocker-api that creates mocks for REST APIs. It will be helpful when you try to test your application without the actual REST API server.

Features:

🔥 Built in support for hot Mocker file replacement.
🚀 Quickly and easily configure the API via JSON.
🌱 Mock API proxying made simple.
💥 Can be used independently without relying on webpack and webpack-dev-server.

Quick Start

mkdir mocker-app && cd mocker-app

# Create a mocker configuration file based on rules
touch api.js

# Global install dependent.
npm install mocker-api -g

# Default port: 3721
mocker ./api.js

# Designated port
# Run server at localhost:8000
mocker ./api.js --host localhost --port 8000

Installation

you can put it the package.json config as a current project dependency.

npm install mocker-api --save-dev

Usage

mocker-api dev support mock, configured in mocker/index.js.

you can modify the http-proxy options and add the event listeners by adding the httpProxy configuration

const proxy = {
  // Priority processing.
  // apiMocker(app, path, option)
  // This is the option parameter setting for apiMocker
  _proxy: {
    proxy: {
      // Turn a path string such as `/user/:name` into a regular expression.
      // https://www.npmjs.com/package/path-to-regexp
      '/repos/(.*)': 'https://api.github.com/',
      '/:owner/:repo/raw/:ref/(.*)': 'http://127.0.0.1:2018',
      '/api/repos/(.*)': 'http://127.0.0.1:3721/'
    },
    // rewrite target's url path. Object-keys will be used as RegExp to match paths.
    // https://github.com/jaywcjlove/mocker-api/issues/62
    pathRewrite: {
      '^/api/repos/': '/repos/',
    },
    changeHost: true,
    // modify the http-proxy options
    httpProxy: {
      options: {
        ignorePath: true,
      },
      listeners: {
        proxyReq: function (proxyReq, req, res, options) {
          console.log('proxyReq');
        },
      },
    },    
  },
  // =====================
  // The default GET request.
  // https://github.com/jaywcjlove/mocker-api/pull/63
  '/api/user': {
    id: 1,
    username: 'kenny',
    sex: 6
  },
  'GET /api/user': {
    id: 1,
    username: 'kenny',
    sex: 6
  },
  'GET /api/user/list': [
    {
      id: 1,
      username: 'kenny',
      sex: 6
    }, {
      id: 2,
      username: 'kenny',
      sex: 6
    }
  ],
  'GET /api/:owner/:repo/raw/:ref/(.*)': (req, res) => {
    const { owner, repo, ref } = req.params;
    // http://localhost:8081/api/admin/webpack-mock-api/raw/master/add/ddd.md
    // owner => admin
    // repo => webpack-mock-api
    // ref => master
    // req.params[0] => add/ddd.md
    return res.json({
      id: 1,
      owner, repo, ref,
      path: req.params[0]
    });
  },
  'POST /api/login/account': (req, res) => {
    const { password, username } = req.body;
    if (password === '888888' && username === 'admin') {
      return res.json({
        status: 'ok',
        code: 0,
        token: "sdfsdfsdfdsf",
        data: {
          id: 1,
          username: 'kenny',
          sex: 6
        }
      });
    } else {
      return res.status(403).json({
        status: 'error',
        code: 403
      });
    }
  },
  'DELETE /api/user/:id': (req, res) => {
    console.log('---->', req.body)
    console.log('---->', req.params.id)
    res.send({ status: 'ok', message: '删除成功!' });
  }
}
module.exports = proxy;

Options

  • proxy => {} Proxy settings, Turn a path string such as /user/:name into a regular expression.
  • pathRewrite => {} rewrite target's url path. Object-keys will be used as RegExp to match paths. #62
  • withFullUrlPath=false => Boolean the proxy regular expression support full url path. if the proxy regular expression like /test?a=1&b=1 can be matched. #25
  • priority => proxy priority proxy or mocker #151
  • changeHost => Boolean Setting req headers host.
  • httpProxy => {} Set the listen event and configuration of http-proxy
  • bodyParserJSON JSON body parser
  • bodyParserText Text body parser
  • bodyParserRaw Raw body parser
  • bodyParserUrlencoded URL-encoded form body parser
  • bodyParserConf => {} bodyParser settings. eg: bodyParserConf : {'text/plain': 'text','text/html': 'text'} will parsed Content-Type='text/plain' and Content-Type='text/html' with bodyParser.text
  • watchOptions => object Options object as defined chokidar api options
  • header => {} Access Control Allow options.
    {
      header: {
        'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE',
      }
    }

⚠️ No wildcard asterisk * - use parameters instead (.*), support v1.7.3+

Delayed Response

You can use functional tool to enhance mock. #17

const delay = require('mocker-api/delay');
const noProxy = process.env.NO_PROXY === 'true';

const proxy = {
  'GET /api/user': {
    id: 1,
    username: 'kenny',
    sex: 6
  },
  // ...
}
module.exports = (noProxy ? {} : delay(proxy, 1000));

apiMocker

apiMocker(app, mockerFilePath[, options])
apiMocker(app, Mocker[, options])

Multi entry mocker file watching

const apiMocker = require('mocker-api');
const mockerFile = ['./mock/index.js'];
// or
// const mockerFile = './mock/index.js';
apiMocker(app, mockerFile, options)

Example

Using With Command

Base example

⚠️ Not dependent on webpack and webpack-dev-server.

# Global install dependent.
npm install mocker-api -g
# Run server
mocker ./mocker/index.js

Or you can put it the package.json config as a current project dependency.

{
  "name": "base-example",
  "scripts": {
+    "api": "mocker ./mocker"
  },
  "devDependencies": {
+    "mocker-api": "2.9.5"
  },
+  "mocker": {
+    "port": 7788
+  },
  "license": "MIT"
}

Using With Express

Express example

To use api mocker on your express projects.

⚠️ Not dependent on webpack and webpack-dev-server.

const express = require('express');
+ const path = require('path');
+ const apiMocker = require('mocker-api');

const app = express();

+ apiMocker(app, path.resolve('./mocker/index.js'))
app.listen(8080);

or

const express = require('express');
+ const apiMocker = require('mocker-api');

const app = express();

+ apiMocker(app, {
+   'GET /api/user': {
+     id: 1,
+     sex: 0
+   }
+ });

app.listen(8080);

Using With Webpack

webpack example

To use api mocker on your Webpack projects, simply add a setup options to your webpack-dev-server options:

Change your config file to tell the dev server where to look for files: webpack.config.js.

const HtmlWebpackPlugin = require('html-webpack-plugin');
+ const path = require('path');
+ const apiMocker = require('mocker-api');

module.exports = {
  entry: {
    app: './src/index.js',
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
+ devServer: {
+   ...
+   before(app){
+     apiMocker(app, path.resolve('./mocker/index.js'), {
+       proxy: {
+         '/repos/(.*)': 'https://api.github.com/',
+         '/:owner/:repo/raw/:ref/(.*)': 'http://127.0.0.1:2018'
+       },
+       changeHost: true,
+     })
+   }
+ },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve('./public/index.html'),
      title: 'Webpack App Mocker API'
    })
  ],
};

Must have a file suffix! For example: ./mocker/index.js.

Let's add a script to easily run the dev server as well: package.json

{
  "name": "development",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
+    "start": "webpack serve --progress --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "html-webpack-plugin": "4.5.0",
    "mocker-api": "2.9.5",
    "webpack": "5.22.0",
    "webpack-cli": "4.5.0",
    "webpack-dev-server": "3.11.2"
  }
}

Mock API proxying made simple.

{
  before(app){
+   apiMocker(app, path.resolve('./mocker/index.js'), {
+     proxy: {
+       '/repos/(.*)': 'https://api.github.com/',
+     },
+     changeHost: true,
+   })
  }
}

Using With create-react-app

create-react-app example

To use api mocker on your create-react-app projects. create src/setupProxy.js and place the following contents in it:

+ const apiMocker = require('mocker-api');
+ const path = require('path');

module.exports = function(app) {
+  apiMocker(app, path.resolve('./mocker/index.js'), {
+    proxy: {
+      '/repos/(.*)': 'https://api.github.com/',
+    },
+    changeHost: true,
+  });
};
{
  .....
  "devDependencies": {
+    "mocker-api": "2.9.5"
  },
  ....
}

Development

$ yarn install
$ yarn run build
$ yarn run watch
$ yarn run test

Contributors

As always, thanks to our amazing contributors!

Made with github-action-contributors.

License

MIT © Kenny Wong

mocker-api's People

Contributors

aizigao avatar arloduff avatar avin avatar chaosforfun avatar dependabot[bot] avatar elfman avatar fearclear avatar hfuuss avatar jaywcjlove avatar ksky521 avatar kud avatar matissjanis avatar renovate-bot avatar renovate[bot] avatar scarcoco avatar syhmosh avatar terence-cheng avatar vanpipy avatar xiongamao avatar yehq avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mocker-api's Issues

proxy did not work

We use webpack-api-mocker for mocking our endpoint, but now want to implement one, so we tried this:

apiMocker(app, path.resolve('config/mocker.js'), {
  proxy: {
    '/ml/customer//*': 'http://localhost:8086/'
  },
  changeHost: true
})

like in the readme and example. But it never fetches from :8068 but still from mocker.js. Sorry if it isn't an issue but my misconfiguration.

Best, Sven

指定cookie

和webpack一起使用,将请求转发到远程服务器时,怎样在本地开发文件指定cookie?
如果不带cookie,没有权限使用远程服务器接口。

谢谢

req.params not populating correctly

A request to /api/user/1 will give undefined for req.params.id:

'GET /api/user/:id': (req, res) => {
  console.log('---->', req.params.id)     // undefined
  console.log('---->', req.params)        // { '0': 'api/user/1' }
  res.send({ status: 'ok' });
}

Do you have any ideas? Perhaps we could add some tests?

建议把配置和MOCK 拆分开来

  1. 配置_proxy 和 接口MOCK 是否应该拆分开来?
  2. chokidar 的配置是否可以支持传入?
  3. 目前看 watch 了整个目录,但是获取 mock 数据 还是单纯重传入的 watchFile 获取,没有而不是 watch 的文件自动导入,比如在watchFile 中引入其他文件?

proxy 参数不支持设置请求头

目前只能通过 changeHost 来设置 host,其他的诸如 cookie,origin,referer 都不能设置。
如果代理到线上环境,经常会遇到鉴权失败,请求添加该功能哦~

建议把 proxy 配置对象的值改为一个 object,内容就是请求头内容,如何呢?

how to pass NO_PROXY

vue-cli3

in vue.config.js

"scripts": {
"debug": vue-cli-service serve -- --NO_PROXY=true
}

does not work

Websocket support

Thanks for this package, it's working great!
But how could I integrate this with Socket.io or SockJS? I need to mock these too.
My application have a REST-API that I mock with webpack-api-mocker during development, but my application also pushes updates with websocket and I need to be able mock these to. Can I get the HTTP-handler from webpack-api-mocker somehow, or could I create one myself and provide it to webpack-api-mocker?
https://github.com/sockjs/sockjs-node

请求体不能正常解析 req.query和req.body不正确

举例 Content-Type: application/x-www-form-urlencoded; charset=utf-8
将会解析请求体失败
若是类似 $.get("/user?id=12") 也会解析请求失败。
另外mock文件夹下的文件是commonjs语法,可以统一用esm的 import 和 export 语法。那样就做到了除框架外的开发代码风格统一了。

我自己借鉴你的写了一个,多引了一个 "esm" node_modules 用来统一使用 ESM 代码风格。然后支持监控整个文件夹。

const path = require("path");
const chokidar = require("chokidar");
const bodyParser = require("body-parser");
const pathToRegExp = require("path-to-regexp");
const requireEsModule = require("esm")(module);
const dir = path.join.bind(path, __dirname);
/**
 * routeMatch
 * 路由路径 和 pathname 进行匹配
 * @param {String} route 路由路径 如/user/:id
 * @param {String} pathname 浏览器 pathname 如/user/12
 * @param {Object,other} config 可选 路径匹配规则配置
 * @returns {Object,false} 不匹配时返回false
 */
const routeMatch = (route, pathname, config) => {
	config = Object.assign({
		sensitive: true,
		strict: false,
		end: true,
		start: true,
	}, config);
	const keys = [];
	const reg = pathToRegExp(route, keys, config);
	const vals = reg.exec(pathname);
	if (!vals) {
		return false;
	}
	const res = {};
	keys.forEach(
		({ name }, idx) => (res[name] = vals[idx + 1])
	);
	return res;
};

const clearRequireCache = file => {
	const data = require.cache[file] || {};
	const list = data.parent && data.parent.children;
	list && list.splice(list.indexOf(data), 1);
	delete require.cache[file];
};
const clearRequireEsModule = mo => {
	let file, data;
	try {
		file = require.resolve(mo);
	} catch (e) {
		console.log(e); // eslint-disable-line
	}
	clearRequireCache(file || mo);
	try {
		data = file && requireEsModule(file);
	} catch (e) {
		console.log(e); // eslint-disable-line
	}
	return data;
};

const moduleMap = {};
const addModule = file => {
	const esm = clearRequireEsModule(file);
	moduleMap[file] = (esm && esm.default) || esm || {};
};
const delModule = file => (delete moduleMap[file]);
const moduleToRoute = () => {
	const routeMap = {};
	const routes = Object.assign({},
		...Object.values(moduleMap));
	Object.keys(routes).forEach(k => {
		if (k === "NO_MOCK") {
			return (routeMap[k] = routes[k]);
		}
		let [, method = "all", route = ""] =
			k.match(/^(\S+)\s+(\W.*)$/) || [];
		if (route) {
			method = method.toLowerCase();
			route = route.replace(/\s+/g, "");
			method === "method" && (method = "all");
			routeMap[route] = Object.assign({},
				routeMap[route], { [method]: routes[k] });
		}
	});
	return routeMap;
};

const webpackMock = (app, folder = "mock") => {
	// app.use(require("multer")().none()); // 支持FormData
	app.use(bodyParser.json());
	app.use(bodyParser.text({ type: "text/xml" }));
	app.use(bodyParser.text({ type: "text/html" }));
	app.use(bodyParser.raw({ type: "text/plain" }));
	app.use(bodyParser.urlencoded({ extended: false }));
// 这部分有大bug 会影响带有请求体的请求,使得在devServer.proxy内设置的代理出现问题,大致原因是自动做了请求体的解析,导致代理转发出错

	let timer;
	let routeMap = {};
	const calc = () => (routeMap = moduleToRoute());

	app.all("*", (req, res, next) => {
		if (routeMap.NO_MOCK) {
			return next();
		}
		const method = req.method.toLowerCase();
		const pathname = req.path;
		let params;
		const route = Object.keys(routeMap).find(k => {
			params = routeMatch(k, pathname);
			return Boolean(params);
		});
		const handler = routeMap[route] || {};
		const callback = method in handler
			? handler[method] : handler.all;
		if (callback) {
			req.params = params || {};
			typeof callback === "function"
				? callback(req, res, next)
				: res.json(callback);
		} else {
			// res.json 和 next 不能同时使用
			next();
		}
	});
	const mock = dir(folder);
	// https://www.npmjs.com/package/chokidar
	chokidar.watch(mock).on("all", (event, info) => {
		switch (event) {
			case "add": addModule(info); break;
			case "unlink": delModule(info); break;
			case "change": addModule(info); break;
			case "error": break;
			default: break;
		}
		// 防抖 频繁触发只有500ms内无触发才会执行
		timer && clearTimeout(timer);
		timer = setTimeout(calc, 500);
	});
};

module.exports = webpackMock;

可以一起学习
mock api示例
如果需要还可以支持formData形式的纯文本请求体 解析,不过需要引入依赖"multer" 代码中那一行被我注释了

基本使用请求代理如何重写path?

我想在访问 http://localhost/api/client/xxx 的时候,代理到 http://10.1.44.95:8080/sz/api/,所以我写了如下配置:

/* eslint-disable */
const delay = require('mocker-api/utils/delay');

const proxy = {
  _proxy: {
    proxy: {
      '/api/client/(.*)': 'http://10.1.44.95:8080/sz/api/'
    },
    changeHost: true,
  },
};

module.exports=delay(proxy, 0);

但是在请求的时候还是会把/api/client带过去

$ curl http://localhost:3721/api/client/12
{"timestamp":1576654898376,"status":404,"error":"Not Found","message":"Not Found","path":"/sz/api/api/client/12"}

我想要的效果是访问 http://localhost:3721/api/client/12, 就代理到 /sz/api/12

看到 webpack 里面可以用 pathRewrite,单独使用没有找到设置方法

试了好多配置,貌似没有效果啊。。

api路径匹配不正确

很好用的插件, 发现一个BUG:
例如:

GET /api/jobs

这个请求会把它之后类似:

GET /api/jobs/:id
GET /api/jobs/:id/detail

这样的请求全部拦截了

可以监听mock文件新增吗

试了下可以加载/mock/* 下的文件了,也可以监听到文件的修改
但是在项目起来之后去新增mock文件就监听不到了,这个可以支持一下吗
或者第2个参数支持传目录?比如 /mock/ 这样,监听文件变动?
apiMocker(app, mockerFile, options)

建议新增可自定义的Access-Control-Allow-Headers数组配置项

代码 94 行

let origin = req.get('Origin') || '*'
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, accesskey');
res.setHeader('Access-Control-Allow-Credentials', true);

Access-Control-Allow-Headers 建议以配置数组的方式,merge其中的字段,比如我司需要accesskey 这个扩展字段。

否则将会报错:

origin 'http://local.xxx.com' has been blocked by CORS policy: Request header field accesskey is not allowed by Access-Control-Allow-Headers in preflight response.

Proxy didn't work when proxy and API endpoint configs both exist

Environment

"mocker-api": "^1.12.2"

Issue

I have an back-end API server running locally on port 2080, and I want my front-end which running locally as well to call this local API server, because I want to do integrate test between front-end and back-end.
But I found that Proxy didn't work when proxy and API endpoint configs both exist(just returned the response.json, and API server didn't receive any request ):

(Chinese translation) 我在本地有前端和后端两个服务,后端API server运行于端口2080,如下, 如果我同时配置proxy和endpoint,只会返回/response.json,并没有proxy到2080的API server。这无法完成本地前后端联调测试的需求。

const proxy = {
  _proxy: {
    proxy: {
      '/api/v1/(.*)': 'http://localhost:2080/'
    }
  },

  // API endpoint describe here
   'GET /api/v1/login/:userId': (req, res) => {
     return res.json(require('./response.json'));
   }
 
};
module.exports = proxy;

If I remove the endpoint config, front end will call proxy which is http://localhost:2080/:

(Chinese translation) 如果我删除endpoint配置,只留proxy,这时/api/v1/login/可以转发到我的本地2080 API server中。

const proxy = {
  _proxy: {
    proxy: {
      '/api/v1/(.*)': 'http://localhost:2080/'
    }
  },

  // API endpoint describe here  (REMOVE IT !)
  // 'GET /api/v1/login/:userId': (req, res) => {
  //    return res.json(require('./response.json'));
  // }
 
};
module.exports = proxy;

Then the API server locally will receive request call for /api/v1/login/:userId now.


Please help about what's wrong here?
Thanks

安装指定版本报错

想问下我直接npm安装的是1.4.2版本,指定1.4.3版本安装会报错是什么情况?

报错信息:

npm ERR! Darwin 17.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/lib/node_modules/cnpm/node_modules/.bin/npm" "--userconfig=/Users/Tracy/.nenpmrc" "--disturl=https://npm.taobao.org/mirrors/node" "--registry=http://rnpm.hz.netease.com/" "--cache=/Users/Tracy/.nenpm/.cache" "install"
npm ERR! node v9.2.1
npm ERR! npm v3.10.10
npm ERR! code ETARGET

npm ERR! notarget No compatible version found: webpack-api-mocker@^1.4.3
npm ERR! notarget Valid install targets:
npm ERR! notarget 1.4.2, 1.4.0
npm ERR! notarget
npm ERR! notarget This is most likely not a problem with npm itself.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! notarget
npm ERR! notarget It was specified as a dependency of 'st-leave-message'

监听多个mock文件启动速度很慢,有什么优化方式么

 Done:  Hot Mocker /mock/.gitkeep file replacement success!
 Done:  Hot Mocker /mock/account.js file replacement success!
 Done:  Hot Mocker /mock/activity.js file replacement success!
 Done:  Hot Mocker /mock/address.js file replacement success!
 Done:  Hot Mocker /mock/agent.js file replacement success!
 Done:  Hot Mocker /mock/bank.js file replacement success!
 Done:  Hot Mocker /mock/cart.js file replacement success!
 Done:  Hot Mocker /mock/commodity.js file replacement success!
 Done:  Hot Mocker /mock/config.js file replacement success!
 Done:  Hot Mocker /mock/contacts.js file replacement success!
 Done:  Hot Mocker /mock/message.js file replacement success!
 Done:  Hot Mocker /mock/order.js file replacement success!
 Done:  Hot Mocker /mock/shop.js file replacement success!
 Done:  Hot Mocker /mock/statis.js file replacement success!
 Done:  Hot Mocker /mock/team.js file replacement success!

启动时间很长

Mock下面多个文件时,监听有报错

版本:^1.5.9

初始化npm run dev 不报错,当修改Mock下的文件时,报错...

Failed: Hot Mocker file replacement failed!!

追踪代码后发现:

  // 释放老模块的资源
  function cleanCache(modulePath) {
    var module = require.cache[modulePath];
    // remove reference in module.parent
    if (module.parent) {   //这行报错
      module.parent.children.splice(module.parent.children.indexOf(module), 1);
    }
    require.cache[modulePath] = null;
  }

上面的报错被捕捉到了

watcher.on('all', function (event, path) {
    if (event === 'change' || event === 'add') {
      try {
        // 当监听的可能是多个配置文件时,需要清理掉更新文件以及入口文件的缓存,重新获取
        cleanCache(path);
        if (path !== watchFile) {
          cleanCache(watchFile);
        }

        proxy = require(watchFile);

        console.log(`${` Done: `.green_b.black} Hot Mocker ${watchFile.replace(process.cwd(), '').green} file replacement success!`);
      } catch (ex) {
        console.error(`${` Failed: `.red_b.black} Hot Mocker file replacement failed!!`);
      }
    }
  })

作者的本意似乎想监听mock下的修改,清掉缓存文件,怎么就报错了呢???

TypeError: Cannot read property 'replace' of undefined

The problem

The error TypeError: Cannot read property 'replace' of undefined is thrown when contentType is undefined. Seems to be caused by 49358ca

This is problematic for users such as myself, who use Axios, which deliberately strips out a Content-Type header from any request which is not sending data, even if one is provided. See axios/axios#86

Steps to reproduce

Send a request to your mock-api which does not have a Content-Type header. Using Axios, you can send something similar to:

this.axios.get(url), {
  headers: {
    'Content-Type': 'application/json',
    Accept: 'application/json'
  },
  params: {
    // Your parameters here
  }
}).then(result => result.data)

Mocker-api will fail with the error TypeError: Cannot read property 'replace' of undefined because contentType will come out as undefined, even though it was provided.

I understand you may argue that Axios should not be stripping out the Content-Type from the request; however, it's still a good practice for this codebase to check for one before calling replace on a variable which may be undefined.

proxy 不工作

versions:
vue-cli 3

  devServer: {
    before(app) {
      apiMocker(app, path.resolve('./mock/index.js'), {
        proxy: {
          '/passport/*': 'http://api.user.com',
        },
        changeHost: true,
      });
    },
    open: true,
    host: '0.0.0.0',
    port: 8080,
    https: false,
    hotOnly: false,
....

mock/index.js

const noProxy = process.env.NO_PROXY === 'true';

const proxy = {
  'GET /user/passport/login': (req, res) => {
    console.log('get /passport/login');
    return res.json({
      status: 302,
      msg: 'xxxxxxx'
    });
  },
  'POST /user/passport/login': (req, res) => {
    console.log('post /passport/login');
    return res.json({
      status: 303,
      msg: 'yyyyyyy'
    });
  }
};

module.export = noProxy ? {} : proxy;

postman 返回信息是 Cannot POST /user/passport/login

Params are not able to contain any hyphens in the string

Currently the params are not allowed to have any hyphens

Example:
If we set the mock endpoint to be GET /api/:userId, and we hit it with a GET request to /api/2342a-234ab-342, it returns a 404. Otherwise if we make a GET request to /api/2342a234ab342, the call succeeds.

请求路径匹配的问题

请问对于带query的get请求如何匹配,试了半天没有成功

/test?action=config&&noCache=1540892048678

这个地址还不太正常,&多一个,noCache参数如何匹配,有没有正则匹配的方式,、

Hot Mocker broken

Using example webpack project with node v11.14.0 fails doing hot reloads.

 Failed:  Hot Mocker /mocker/index.js file replacement failed!!
 Failed:  Hot Mocker /mocker/user.js file replacement failed!!

fs.watch问题

问题:在mac pro上运行,发现fs.watch无法实时监听mock.js文件的变化
解决:将fs.watch改为fs.watchFile,再加参数{ interval: 1000 }。

Delay

如何加入延时返回呢?类似于这种东西
rrj oipwbfsc8mu 2 l0 94

mock/index.js中不能使用import吗

import { ARTICLE } from '@/api'
const noProxy = process.env.NO_PROXY === 'true'
const proxy = {
// POST ${ARTICLE.release}: (req, res) => {
[POST ${ARTICLE.release}]: (req, res) => {
console.log('post /release')
return res.json({
status: 303,
msg: '操作次数过多'
})
}
}

module.exports = noProxy ? {} : proxy

SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:599:28)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)

需要可配置bodyParser的limit

默认的是100k, 希望能改成可配置的,谢谢

let bodyParserMethd = bodyParser.json({ limit });
const contentType = req.get('Content-Type');
if (contentType === 'text/plain') {
	bodyParserMethd = bodyParser.raw({limit,  type: 'text/plain' });
} else if (contentType === 'text/html') {
	bodyParserMethd = bodyParser.text({limit, type: 'text/html' });
} else if (contentType === 'application/x-www-form-urlencoded') {
	bodyParserMethd = bodyParser.urlencoded({ limit, extended: false });
}

是否可以增加 自動重新啟動的特性

Hi. 我使用下面這個方式來進行載入 mock 文件
能不能讓 更改 mock json 數據自動更新?

const delay = require('mocker-api/utils/delay');
const requireContext = require('require-context');

const db = requireContext('../../src/services/mock', true, /\.mock\.js$/);

// 延遲回應時間 (模擬 Loading 效果)
const delayTime = 1500;

function loadMockyFiles() {
    let mockProxy = {};
    db.keys().forEach(filename => {
        mockProxy = {...mockProxy, ...db(filename)};
    });
    return mockProxy;
}
const proxy = loadMockyFiles();
module.exports = delay(proxy, delayTime);

Axios 无法拦截mocker-api请求

Axios.interceptors.request.use(config => {
console.log(config);
return config
})

代码如上,经测试。只有通过 mocker-api 代理转发的请求可以被拦截打印处配置
未经过代理直接访问 mocker-api 数据的请求,无法被拦截。
请问是我疏忽了mocker-api 的哪个配置吗

mock的自定义函数中的req获取不到body

webpack配置:
before(app) {
apiMocker(app, path.resolve('./mock/index.js'), {
changeHost: true,
})
}
mock/index.js文件
'POST /ajax/getCustomerDetailInfo.json': (req, res) => {
const {cust_no} = req.body;
console.log(req.body, req.params, req.query);
})
无论是post测试还是实际代码测试:
wx20180807-150738 2x

结果都是:
{} {} {}

在devServer的before钩子里配置的proxy,是会检查host的可用性么?

const apiDomainMap = {
'/ccs/api/getLoginInfo': 'https://taobao.com'
};
以上的配置 可以正常反向代理没有问题
const apiDomainMap = {
'/ccs/api/getLoginInfo': 'https://neibu-api.com'
};
以上的配置 反向代理失败 还是会用以前的 neibu:8084
neibu-api.com XX.XX.XX.XX // 这个是配置host的域名

所以是因为https://neibu-api.com域名不可用 所以能反向代理么?
不会是匹配规则的问题 因为试了taobao是可以正常代理过去的

Watch polling

If served from devvm can't detect changes. Polling could solve this. chokidar has config property usePolling,

使用proxy时报错

浏览器报错如下:

TypeError: Unexpected MODIFIER at 7, expected END
    at mustConsume (... \node_modules\mocker-api\node_modules\path-to-regexp\dist\index.js:113:15)
    at parse (... \node_modules\mocker-api\node_modules\path-to-regexp\dist\index.js:172:9)
    at stringToRegexp (D:\yukippe\memberCenter\node_modules\mocker-api\node_modules\path-to-regexp\dist\index.js:329:27)
    at pathToRegexp (... \node_modules\mocker-api\node_modules\path-to-regexp\dist\index.js:403:12)
    at  ... \node_modules\mocker-api\src\index.js:83:16
    at Array.find (<anonymous>)
    at ... \node_modules\mocker-api\src\index.js:82:45
    at Layer.handle [as handle_request] (... \node_modules\express\lib\router\layer.js:95:5)
    at next (... \node_modules\express\lib\router\route.js:137:13)
    at next (... \node_modules\express\lib\router\route.js:131:14)

使用方式如下
系统:win10
webpack.config.js:

  devServer: {
...
    before(app){
      apiMocker(app, path.resolve('./mock/mock.js'))
    },
  }, 

mock.js :

const _proxy = process.env.proxy == 'true';
let proxy = {};
if(_proxy) {
  proxy={
    _proxy : {
      proxy : {
        "/api/*":"http://127.0.0.1:9090/"
      },
      changeHost: true
    }
  };
} else {
  proxy = {
    'GET /api/user': {id: 1, username: 'kenny', sex: 6 },
    'GET /api/user/list': [
      {id: 1, username: 'kenny', sex: 6 },
      {id: 2, username: 'kenny', sex: 6 }
    ],
    'POST /api/login/account': (req, res) => {
      const { password, username } = req.body;
      if (password === '888888' && username === 'admin') {
        return res.send({
          status: 'ok',
          code: 0,
          token: "sdfsdfsdfdsf",
          data: {id: 1, username: 'kenny', sex: 6 }
        });
      } else {
        return res.send({status: 'error', code: 403 });
      }
    },
    'DELETE /api/user/:id': (req, res) => {
      console.log('---->', req.body)
      console.log('---->', req.params.id)
      res.send({ status: 'ok', message: '删除成功!' });
    }
  }
}
module.exports = proxy

当使用proxy时候, 浏览器就会出现上述错误。
使用example/webpack 同样会出现path-to-regexp相关的错误

没有配置在proxy对象里面的其他接口可以不走mocker吗

const proxy = {
    'POST /busresapi/supplier/getChannelCfg':{
        "header": {
            "isSuccess": true,
            "errCode": "EC_ALL_00000",
            "errMsg": "操作成功"
        }
    },
    'POST /wxbusapi/menuLayoutConfig/getMenuLayout': {
        "header": {
            "isSuccess": false
        }
    }
}
module.exports = proxy

除了以上两个配置的接口,其他接口请求的时候可以不走mocker吗?
貌似现在都走了mocker,但是proxy 里面没有配置,就会404,这是正常的现象吗?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.