<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          mocker-api為REST API創(chuàng)建模擬API

          聯(lián)合創(chuàng)作 · 2023-10-01 16:57

          mocker-api 為 REST API 創(chuàng)建模擬 API。 當(dāng)您嘗試在沒有實(shí)際 REST API 服務(wù)器的情況下測(cè)試應(yīng)用程序時(shí),它會(huì)很有用。

          特征:

          ??內(nèi)置支持熱Mocker文件替換。
          ??通過JSON快速輕松地配置API。
          ??模擬API代理變得簡單。
          ??可以獨(dú)立使用,無需依賴webpack和webpack-dev-server。

          快速開始

          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
          # Run server
          mocker ./api.js

          安裝

          你可以將 package.json 配置作為當(dāng)前項(xiàng)目依賴項(xiàng)。

          npm install mocker-api --save-dev

          使用

          mocker-api 在開發(fā)模式支持模擬數(shù)據(jù), 將入口文件放入 mocker/index.js.

          您可以通過添加 httpProxy 配置來修改 http-proxy 選項(xiàng)并添加事件偵聽器

          const proxy = {
            // Priority processing.
            // apiMocker(app, path, option)
            // This is the option parameter setting for apiMocker
            _proxy: {
              proxy: {
                '/repos/(.*)': 'https://api.github.com/',
                '/:owner/:repo/raw/:ref/(.*)': 'http://127.0.0.1:2018'
              },
              changeHost: true,
              // modify the http-proxy options
              httpProxy: {
                options: {
                  ignorePath: true,
                },
                listeners: {
                  proxyReq: function (proxyReq, req, res, options) {
                    console.log('proxyReq');
                  },
                },
              },    
            },
            // =====================
            '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;

          參數(shù)選項(xiàng)

          • proxy => {} Proxy settings.
          • changeHost => {} 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

          ?? 沒有通配符 * - 使用參數(shù) (.*), suport v1.7.3+

          延遲反應(yīng)

          你可以使用工具自帶方法增強(qiáng)模擬. #17

          const delay = require('mocker-api/utils/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, mocker[,proxy])

          多入口mocker 文件監(jiān)聽

          const mockerFile = ['./mock/index.js'];
          // or
          // const mockerFile = './mock/index.js';
          apiMocker(app, mockerFile, proxy)

          在命令行中使用

          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": "^1.6.4"
            },
            "license": "MIT"
          }

          在 Express 中使用

          Express example

          ?? 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);

          在 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',
              print: './src/print.js'
            },
            devtool: 'inline-source-map',
          + 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({
                title: 'Development'
              })
            ],
            output: {
              filename: '[name].bundle.js',
              path: require.resolve(__dirname, 'dist')
            }
          };

          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-dev-server --open",
                "build": "webpack"
              },
              "keywords": [],
              "author": "",
              "license": "MIT",
              "devDependencies": {
                ....
              }
            }

          模擬API代理簡單模式。

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

           

           

          瀏覽 31
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          編輯 分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          編輯 分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  国产一卡二卡在线看 | 激情中文字幕在线观看 | 大香蕉免费成人 | 国产91又粗又大又爽的视频网站 | 暴操无毛黑丝在线观看 |