叶氏吊机 發表於 2019-10-26 16:50:00

node.js 接口调用示例

<p>测试用例git地址(node.js部分):https://github.com/wuyongxian20/node-api.git</p>
<p>项目架构如下:</p>
<p><img src="https://img2018.cnblogs.com/blog/451237/201910/451237-20191026164317400-1831143192.png" alt="" width="314" height="400"></p>
<p>controllers:</p>
<p>  文件夹下为接口文件</p>
<p>logs:</p>
<p>  log4js 日志打印文件</p>
<p>mongodb:</p>
<p>  mongodb数据库配置及帮助类的封装</p>
<p>mysql:</p>
<p>  mysql数据库配置及数据库的封装</p>
<p>utils:</p>
<p>  帮助类</p>
<p>app.js:</p>
<p>  node.js启动文件</p>
<p>controller.js:</p>
<p>  controller接口封装调用</p>
<p>&nbsp;</p>
<p>相互关系:</p>
<p>&gt;package.json 项目依赖</p>
<p>&gt;mongodb和mysql为基本的数据库配置和帮助类</p>
<p>&gt;controllers文件夹下的接口引用mongodb和mysql操作数据库</p>
<p>&gt;controller.js是对controllers文件夹的引用和设置api路由跳转</p>
<p>&gt;app.js 加载controller.js文件,即加载所有的controllers文件夹下的接口</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>VUE+Node.js接口调用步骤</p>
<p><strong>MySql数据库准备</strong></p>
<p>&gt;mysql 添加测试数据库 rehab(数据库名只需要和mysql\config\index.js中配置文件的数据库名对应起来就行)</p>
<p>&gt;添加测试表test{id:int,name:varchar}</p>
<p><strong>Node.js接口部分</strong>(示例中不考虑mongodb数据库使用部分)</p>
<p><strong>1、创建node.js项目</strong>,向package.json中写入项目需要的依赖文件,依次是</p>
<div class="cnblogs_code"><img id="code_img_closed_b1c912cb-4715-4016-b30e-9337b19ca51f" class="code_img_closed" src="https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt=""><img id="code_img_opened_b1c912cb-4715-4016-b30e-9337b19ca51f" class="code_img_opened" style="display: none" src="https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="">
<div id="cnblogs_code_open_b1c912cb-4715-4016-b30e-9337b19ca51f" class="cnblogs_code_hide">
<pre><span style="color: rgba(0, 0, 0, 1)">{
</span>"name": "node-demo"<span style="color: rgba(0, 0, 0, 1)">,
</span>"version": "1.0.0"<span style="color: rgba(0, 0, 0, 1)">,
</span>"description": "node demo"<span style="color: rgba(0, 0, 0, 1)">,
</span>"main": "app.js"<span style="color: rgba(0, 0, 0, 1)">,
</span>"scripts"<span style="color: rgba(0, 0, 0, 1)">: {
    </span>"start": "supervisor app.js"<span style="color: rgba(0, 0, 0, 1)">
},
</span>"keywords"<span style="color: rgba(0, 0, 0, 1)">: [
    </span>"koa"<span style="color: rgba(0, 0, 0, 1)">,
    </span>"async"<span style="color: rgba(0, 0, 0, 1)">
],
</span>"author": "Michael Liao"<span style="color: rgba(0, 0, 0, 1)">,
</span>"license": "Apache-2.0"<span style="color: rgba(0, 0, 0, 1)">,
</span>"repository"<span style="color: rgba(0, 0, 0, 1)">: {
    </span>"type": "git"<span style="color: rgba(0, 0, 0, 1)">,
    </span>"url": "https://github.com/michaelliao/learn-javascript.git"<span style="color: rgba(0, 0, 0, 1)">
},
</span>"dependencies"<span style="color: rgba(0, 0, 0, 1)">: {
    </span>"koa": "^2.8.1"<span style="color: rgba(0, 0, 0, 1)">,
    </span>"koa-bodyparser": "^4.2.1"<span style="color: rgba(0, 0, 0, 1)">,
    </span>"koa-router": "^7.4.0"<span style="color: rgba(0, 0, 0, 1)">,
    </span>"mongodb": "^3.3.2"<span style="color: rgba(0, 0, 0, 1)">,
    </span>"mysql": "^2.17.1"<span style="color: rgba(0, 0, 0, 1)">,
    </span>"q": "^1.5.1"<span style="color: rgba(0, 0, 0, 1)">,
    </span>"log4js": "^5.2.0"<span style="color: rgba(0, 0, 0, 1)">
}
}</span></pre>
</div>
<span class="cnblogs_code_collapse">package.json</span></div>
<p>koa:koa框架</p>
<p>koa-bodyparser:解析表单数据,并放入到ctx.request.body</p>
<p>koa-router:路由</p>
<p>mongod:node的mongodb数据库中间件</p>
<p>mysql:node的mysql数据库中间件</p>
<p>q:Promise处理模块</p>
<p>log4js:日志文件</p>
<p><strong>2、controller.js</strong> ,设置GET\POST\PUT\DELETE四种接口的路由,并把controllers文件夹下的所有js文件加载进来</p>
<div class="cnblogs_code"><img id="code_img_closed_1401a1c8-be1f-43f9-89b5-e772d7f9c0fb" class="code_img_closed" src="https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt=""><img id="code_img_opened_1401a1c8-be1f-43f9-89b5-e772d7f9c0fb" class="code_img_opened" style="display: none" src="https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="">
<div id="cnblogs_code_open_1401a1c8-be1f-43f9-89b5-e772d7f9c0fb" class="cnblogs_code_hide">
<pre>const fs = require('fs'<span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> add url-route in /controllers:</span>

<span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> addMapping(router, mapping) {
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> (<span style="color: rgba(0, 0, 255, 1)">var</span> url <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> mapping) {
      </span><span style="color: rgba(0, 0, 255, 1)">if</span> (url.startsWith('GET '<span style="color: rgba(0, 0, 0, 1)">)) {
            </span><span style="color: rgba(0, 0, 255, 1)">var</span> path = url.substring(4<span style="color: rgba(0, 0, 0, 1)">);
            router.get(path, mapping);
         </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> console.log(`register URL mapping: GET ${path}`);</span>
      } <span style="color: rgba(0, 0, 255, 1)">else</span> <span style="color: rgba(0, 0, 255, 1)">if</span> (url.startsWith('POST '<span style="color: rgba(0, 0, 0, 1)">)) {
            </span><span style="color: rgba(0, 0, 255, 1)">var</span> path = url.substring(5<span style="color: rgba(0, 0, 0, 1)">);
            router.post(path, mapping);
         </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> console.log(`register URL mapping: POST ${path}`);</span>
      } <span style="color: rgba(0, 0, 255, 1)">else</span> <span style="color: rgba(0, 0, 255, 1)">if</span> (url.startsWith('PUT '<span style="color: rgba(0, 0, 0, 1)">)) {
            </span><span style="color: rgba(0, 0, 255, 1)">var</span> path = url.substring(4<span style="color: rgba(0, 0, 0, 1)">);
            router.put(path, mapping);
            console.log(`register URL mapping: PUT ${path}`);
      } </span><span style="color: rgba(0, 0, 255, 1)">else</span> <span style="color: rgba(0, 0, 255, 1)">if</span> (url.startsWith('DELETE '<span style="color: rgba(0, 0, 0, 1)">)) {
            </span><span style="color: rgba(0, 0, 255, 1)">var</span> path = url.substring(7<span style="color: rgba(0, 0, 0, 1)">);
            router.del(path, mapping);
          </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">console.log(`register URL mapping: DELETE ${path}`);</span>
      } <span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            console.log(`invalid URL: ${url}`);
      }
    }
}

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> addControllers(router, dirs) {
    </span><span style="color: rgba(0, 0, 255, 1)">for</span>(let i=0;i&lt;dirs.length;i++<span style="color: rgba(0, 0, 0, 1)">){
      fs.readdirSync(__dirname </span>+ '/' + dirs).filter((f) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
            </span><span style="color: rgba(0, 0, 255, 1)">return</span> f.endsWith('.js'<span style="color: rgba(0, 0, 0, 1)">);
      }).forEach((f) </span>=&gt;<span style="color: rgba(0, 0, 0, 1)"> {
          </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">console.log(`process controller: ${f}...`);</span>
            let mapping = require(__dirname + '/' + dirs + '/' +<span style="color: rgba(0, 0, 0, 1)"> f);
            addMapping(router, mapping);
      });
    }

}

module.exports </span>= <span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> (dir) {
    let
      controllers_dir </span>= dir || 'controllers'<span style="color: rgba(0, 0, 0, 1)">,
      router </span>= require('koa-router'<span style="color: rgba(0, 0, 0, 1)">)();
      </span><span style="color: rgba(0, 0, 255, 1)">debugger</span><span style="color: rgba(0, 0, 0, 1)">
      let controllers</span>=['controllers','controllers/admin'<span style="color: rgba(0, 0, 0, 1)">]
    addControllers(router, controllers);
   </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> addControllers(router, 'controllers/admin');</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> router.routes();
};


</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> function addControllers(router, dir) {</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">   fs.readdirSync(__dirname + '/' + dir).filter((f) =&gt; {</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">         return f.endsWith('.js');</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">   }).forEach((f) =&gt; {</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">         console.log(`process controller: ${f}...`);</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">         let mapping = require(__dirname + '/' + dir + '/' + f);</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">         addMapping(router, mapping);</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">   });</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)"> }</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> module.exports = function (dir) {</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">   let</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">         controllers_dir = dir || 'controllers',</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">         router = require('koa-router')();</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">         debugger</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">   addControllers(router, controllers_dir);</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">    // addControllers(router, 'controllers/admin');</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">   return router.routes();</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)"> };</span></pre>
</div>
<span class="cnblogs_code_collapse">controller.js</span></div>
<p><strong>3、app.js</strong></p>
<div class="cnblogs_code"><img id="code_img_closed_a5b2d27f-7ca0-42a3-b077-99cf44468538" class="code_img_closed" src="https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt=""><img id="code_img_opened_a5b2d27f-7ca0-42a3-b077-99cf44468538" class="code_img_opened" style="display: none" src="https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="">
<div id="cnblogs_code_open_a5b2d27f-7ca0-42a3-b077-99cf44468538" class="cnblogs_code_hide">
<pre>const Koa = require('koa'<span style="color: rgba(0, 0, 0, 1)">);

const bodyParser </span>= require('koa-bodyparser'<span style="color: rgba(0, 0, 0, 1)">);

const controller </span>= require('./controller'<span style="color: rgba(0, 0, 0, 1)">);

const app </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Koa();

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">log4js 日志配置</span>
<span style="color: rgba(0, 0, 255, 1)">var</span> log4js = require('log4js'<span style="color: rgba(0, 0, 0, 1)">);
log4js.configure(</span>'./config/log4js.json'<span style="color: rgba(0, 0, 0, 1)">);

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> log request URL:</span>
app.use(async (ctx, next) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">添加允许请求头</span>
    ctx.append('Access-Control-Allow-Origin', '*'<span style="color: rgba(0, 0, 0, 1)">)
    ctx.append(</span>'Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'<span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> ctx.append('Content-Type', 'application/json;charset=utf-8')</span>
    ctx.append('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS,PATCH'<span style="color: rgba(0, 0, 0, 1)">)
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">http 预请求处理(post/put/delete 请求在正式请求之前会先发送一个OPTIONS的预请求,只需要把这个OPTIONS的预请求正常返回,后续的请求就会正常执行)</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> (ctx.request.method === 'OPTIONS'<span style="color: rgba(0, 0, 0, 1)">) {
      ctx.body </span>= "OK"<span style="color: rgba(0, 0, 0, 1)">
    } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
      </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">继续执行api请求</span>
<span style="color: rgba(0, 0, 0, 1)">      await next();
    }

});

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> parse request body:</span>
<span style="color: rgba(0, 0, 0, 1)">app.use(bodyParser());

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> add controller:</span>
<span style="color: rgba(0, 0, 0, 1)">app.use(controller());

app.listen(</span>3000<span style="color: rgba(0, 0, 0, 1)">);
console.log(</span>'app started at port 3000...');</pre>
</div>
<span class="cnblogs_code_collapse">app.js</span></div>
<p>app.js做的事情是</p>
<p>&gt;加载koa框架</p>
<p>&gt;加载form参数解析的中间件koa-bodyparser</p>
<p>&gt;加载log4js日志配置文件</p>
<div class="cnblogs_code"><img id="code_img_closed_67ee7e85-6553-4ea2-b56e-1f84c933bf64" class="code_img_closed" src="https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt=""><img id="code_img_opened_67ee7e85-6553-4ea2-b56e-1f84c933bf64" class="code_img_opened" style="display: none" src="https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="">
<div id="cnblogs_code_open_67ee7e85-6553-4ea2-b56e-1f84c933bf64" class="cnblogs_code_hide">
<pre><span style="color: rgba(0, 0, 0, 1)">{
    </span>"appenders"<span style="color: rgba(0, 0, 0, 1)">: {
      </span>"console"<span style="color: rgba(0, 0, 0, 1)">: {
      </span>"type": "console"<span style="color: rgba(0, 0, 0, 1)">
      },
      </span>"trace"<span style="color: rgba(0, 0, 0, 1)">: {
      </span>"type": "dateFile"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"filename": "./logs/access-"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"pattern": ".yyyy-MM-dd.log"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"alwaysIncludePattern": <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">,
      </span>"maxLogSize ": 31457280<span style="color: rgba(0, 0, 0, 1)">
      },
      </span>"http"<span style="color: rgba(0, 0, 0, 1)">: {
      </span>"type": "logLevelFilter"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"appender": "trace"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"level": "trace"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"maxLevel": "trace"<span style="color: rgba(0, 0, 0, 1)">
      },
      </span>"info"<span style="color: rgba(0, 0, 0, 1)">: {
      </span>"type": "dateFile"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"filename": "./logs/info-"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"encoding": "utf-8"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"pattern": ".yyyy-MM-dd.log"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"maxLogSize": 10000000<span style="color: rgba(0, 0, 0, 1)">,
      </span>"alwaysIncludePattern": <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">,
      </span>"layout"<span style="color: rgba(0, 0, 0, 1)">: {
          </span>"type": "pattern"<span style="color: rgba(0, 0, 0, 1)">,
          </span>"pattern": "[%d{ISO8601}][%5p%z%c] %m"<span style="color: rgba(0, 0, 0, 1)">
      },
      </span>"compress": <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">
      },
      </span>"maxInfo"<span style="color: rgba(0, 0, 0, 1)">: {
      </span>"type": "logLevelFilter"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"appender": "info"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"level": "debug"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"maxLevel": "error"<span style="color: rgba(0, 0, 0, 1)">
      },
      </span>"error"<span style="color: rgba(0, 0, 0, 1)">: {
      </span>"type": "dateFile"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"filename": "./logs/error-"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"pattern": ".yyyy-MM-dd.log"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"maxLogSize": 10000000<span style="color: rgba(0, 0, 0, 1)">,
      </span>"encoding": "utf-8"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"alwaysIncludePattern": <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">,
      </span>"layout"<span style="color: rgba(0, 0, 0, 1)">: {
          </span>"type": "pattern"<span style="color: rgba(0, 0, 0, 1)">,
          </span>"pattern": "[%d{ISO8601}][%5p%z%c] %m"<span style="color: rgba(0, 0, 0, 1)">
      },
      </span>"compress": <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">
      },
      </span>"minError"<span style="color: rgba(0, 0, 0, 1)">: {
      </span>"type": "logLevelFilter"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"appender": "error"<span style="color: rgba(0, 0, 0, 1)">,
      </span>"level": "error"<span style="color: rgba(0, 0, 0, 1)">
      }
    },
    </span>"categories"<span style="color: rgba(0, 0, 0, 1)">: {
      </span>"default"<span style="color: rgba(0, 0, 0, 1)">: {
      </span>"appenders"<span style="color: rgba(0, 0, 0, 1)">: [
          </span>"console"<span style="color: rgba(0, 0, 0, 1)">,
          </span>"http"<span style="color: rgba(0, 0, 0, 1)">,
          </span>"maxInfo"<span style="color: rgba(0, 0, 0, 1)">,
          </span>"minError"<span style="color: rgba(0, 0, 0, 1)">
      ],
      </span>"level": "all"<span style="color: rgba(0, 0, 0, 1)">
      }
    }
}</span></pre>
</div>
<span class="cnblogs_code_collapse">log4js.json</span></div>
<p>&gt;加载api路由 controller.js</p>
<p>&gt;请求url处理</p>
<div style="color: rgba(0, 0, 0, 1); font-family: Consolas, &quot;Courier New&quot;, monospace; font-weight: normal; font-size: 16px; line-height: 22px; white-space: pre">
<div class="cnblogs_code">
<pre>app.use(async (ctx, next) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">添加允许请求头</span>
    ctx.append('Access-Control-Allow-Origin', '*'<span style="color: rgba(0, 0, 0, 1)">)
    ctx.append(</span>'Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'<span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> ctx.append('Content-Type', 'application/json;charset=utf-8')</span>
    ctx.append('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS,PATCH'<span style="color: rgba(0, 0, 0, 1)">)
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">http 预请求处理(post/put/delete 请求在正式请求之前会先发送一个OPTIONS的预请求,只需要把这个OPTIONS的预请求正常返回,后续的请求就会正常执行)</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> (ctx.request.method === 'OPTIONS'<span style="color: rgba(0, 0, 0, 1)">) {
      ctx.body </span>= "OK"<span style="color: rgba(0, 0, 0, 1)">
    } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
      </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">继续执行api请求</span>
<span style="color: rgba(0, 0, 0, 1)">      await next();
    }
});</span></pre>
</div>
</div>
<p>  &gt;&gt;ctx.append()</p>
<p>    添加请求头,目的在服务器端解决跨域问题</p>
<p>  &gt;&gt; ctx.request.method === 'OPTIONS'处理</p>
<p>    请求在正式请求之前会先发送一个OPTIONS的预请求,只需要把这个OPTIONS的预请求正常返回,后续的请求就会正常执行</p>
<p>  &gt;&gt;await next()</p>
<p>    当一个中间件调用 next() 则该函数暂停并将控制传递给定义的下一个中间件。当在下游没有更多的中间件执行后,堆栈将展开并    且每个中间件恢复执行其上游行为。</p>
<p>&gt;启动端口监听,启动项目</p>
<p>&nbsp;</p>
<p><strong>4、api接口</strong>(以处理mysql数据的接口为例)</p>
<p>controllers文件夹下创建mysqlapi.js文件</p>
<div class="cnblogs_code"><img id="code_img_closed_fb50c2d7-3c4b-497b-bd6f-a1b18a7f2b25" class="code_img_closed" src="https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt=""><img id="code_img_opened_fb50c2d7-3c4b-497b-bd6f-a1b18a7f2b25" class="code_img_opened" style="display: none" src="https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="">
<div id="cnblogs_code_open_fb50c2d7-3c4b-497b-bd6f-a1b18a7f2b25" class="cnblogs_code_hide">
<pre>let util = require('../utils/util'<span style="color: rgba(0, 0, 0, 1)">)
const db </span>= require('../mysql/mysql.js'<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">var</span> logger = require('log4js').getLogger("index"<span style="color: rgba(0, 0, 0, 1)">);
let util_http </span>= require('../utils/util_http'<span style="color: rgba(0, 0, 0, 1)">)


module.exports </span>=<span style="color: rgba(0, 0, 0, 1)"> {

    </span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
   * 根据数据表名查询全部
   </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
    'GET /mysql/findAll': async (ctx, next) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
      ctx.response.type </span>= 'application/json'<span style="color: rgba(0, 0, 0, 1)">;

      let table </span>=<span style="color: rgba(0, 0, 0, 1)"> ctx.request.query.table
      let sql </span>= `select *<span style="color: rgba(0, 0, 0, 1)"> from ${table}`
      await db.selectAll(sql).then(res </span>=&gt;<span style="color: rgba(0, 0, 0, 1)"> {
            ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.res(res)
      }).</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(err =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
            ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.err(err)
      })
    },
    </span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
   * 根据数据表名和指定查询条件查询
   </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
    'GET /mysql/findBy': async (ctx, next) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
      ctx.response.type </span>= 'application/json'<span style="color: rgba(0, 0, 0, 1)">;
      ctx.append(</span>'Access-Control-Allow-Origin', '*'<span style="color: rgba(0, 0, 0, 1)">)
      let table </span>=<span style="color: rgba(0, 0, 0, 1)"> ctx.request.body.table
      let where </span>=<span style="color: rgba(0, 0, 0, 1)"> ctx.request.body.where
      await db.selectBy(table, where).then(res </span>=&gt;<span style="color: rgba(0, 0, 0, 1)"> {
            ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.res(res)

      }).</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(err =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
            ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.err(err)
      })
    },
    </span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
   * 根据数据表名和id查询
   </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
    'GET /mysql/findById': async (ctx, next) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
      ctx.response.type </span>= 'application/json'<span style="color: rgba(0, 0, 0, 1)">;
      ctx.append(</span>'Access-Control-Allow-Origin', '*'<span style="color: rgba(0, 0, 0, 1)">)
      let table </span>=<span style="color: rgba(0, 0, 0, 1)"> ctx.request.query.table
      let id </span>=<span style="color: rgba(0, 0, 0, 1)"> ctx.request.query.id
      let sql </span>= `select * from ${table} where id='${id}'<span style="color: rgba(0, 0, 0, 1)">`
      await db.selectAll(sql).then(res </span>=&gt;<span style="color: rgba(0, 0, 0, 1)"> {
            ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.res(res)

      }).</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(err =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
            ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.err(err)
      })
    },

    </span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
   * 添加数据
   </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
    'POST /mysql/add': async (ctx, next) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
      </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> ctx.response.type = 'application/json'; </span>
      <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> ctx.res.header('Access-Control-Allow-Origin', '*');</span>

      <span style="color: rgba(0, 0, 255, 1)">if</span> (ctx.req.method == 'POST'<span style="color: rgba(0, 0, 0, 1)">) {
            let data </span>=<span style="color: rgba(0, 0, 0, 1)"> await util_http.getPOSTRes(ctx.req)
            data </span>=<span style="color: rgba(0, 0, 0, 1)"> JSON.parse(data)
            let table </span>=<span style="color: rgba(0, 0, 0, 1)"> data.table
            let params </span>=<span style="color: rgba(0, 0, 0, 1)"> data.params
            await db.insertData(table, params).then(res </span>=&gt;<span style="color: rgba(0, 0, 0, 1)"> {
                ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.res(res)
            }).</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(err =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
                ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.err(err)
            })
      } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            ctx.body </span>= util.err('请求错误'<span style="color: rgba(0, 0, 0, 1)">)
      }


    },
    </span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
   * 更新数据
   </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
    'PUT /mysql/update': async (ctx, next) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
      </span><span style="color: rgba(0, 0, 255, 1)">if</span> (ctx.req.method == 'PUT'<span style="color: rgba(0, 0, 0, 1)">) {
            let data </span>=<span style="color: rgba(0, 0, 0, 1)"> await util_http.getPOSTRes(ctx.req)
            data </span>=<span style="color: rgba(0, 0, 0, 1)"> JSON.parse(data)
            let table </span>=<span style="color: rgba(0, 0, 0, 1)"> data.table
            let sets </span>=<span style="color: rgba(0, 0, 0, 1)"> data.sets
            let where </span>=<span style="color: rgba(0, 0, 0, 1)"> data.where
         </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> console.log('sql', table, sets, where)</span>
            await db.updateData(table, sets, where).then(res =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
                ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.res(res)
            }).</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(err =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
                ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.err(err)
            })
      } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            ctx.body </span>= util.err('请求错误'<span style="color: rgba(0, 0, 0, 1)">)
      }
    },
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> /**</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">* 更新数据</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">*/</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 'PATCH /mysql/patch': async (ctx, next) =&gt; {</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   // ctx.response.type = 'application/json';</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   console.log('patch init')</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   ctx.body = '2222'</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   //ctx.body=util.res('123')</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   // console.log('request',ctx.request)</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   // let table = ctx.request.body.table</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   // console.log('table',table)</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   // let sets = ctx.request.body.sets</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   // let where = ctx.request.body.where</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   // await db.updateData(table, sets, where).then(res =&gt; {</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   //   ctx.body = util.res(res)</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   // }).catch(err =&gt; {</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   //   ctx.body = util.err(err)</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   // })</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> },</span>
    <span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
   * 删除数据
   </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
    'DELETE /mysql/delete': async (ctx, next) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
      let table </span>=<span style="color: rgba(0, 0, 0, 1)"> ctx.request.body.table
      let where </span>=<span style="color: rgba(0, 0, 0, 1)"> ctx.request.body.where
      await db.deleteData(table, where).then(res </span>=&gt;<span style="color: rgba(0, 0, 0, 1)"> {
            ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.res(res)
      }).</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(err =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
            ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.err(err)
      })
    },
    </span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
   * 根据数据表名和id删除数据
   </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
    'DELETE /mysql/deleteById': async (ctx, next) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
      ctx.response.type </span>= 'application/json'<span style="color: rgba(0, 0, 0, 1)">;
      ctx.append(</span>'Access-Control-Allow-Origin', '*'<span style="color: rgba(0, 0, 0, 1)">)
      let table </span>=<span style="color: rgba(0, 0, 0, 1)"> ctx.request.query.table
      let id </span>=<span style="color: rgba(0, 0, 0, 1)"> ctx.request.query.id
      let where </span>=<span style="color: rgba(0, 0, 0, 1)"> {
            id: id
      }
      await db.deleteData(table, where).then(res </span>=&gt;<span style="color: rgba(0, 0, 0, 1)"> {
            ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.res(res)
      }).</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(err =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
            ctx.body </span>=<span style="color: rgba(0, 0, 0, 1)"> util.err(err)
      })
    }
};</span></pre>
</div>
<span class="cnblogs_code_collapse">node.js api接口示例</span></div>
<p>&gt;get 接口中使用ctx.request.query接收Params方式传递的表单参数</p>
<p>&gt;post接口中使用ctx.request.body接收body方式传递的表单参数</p>
<p>  &gt;&gt;post接口中,需要使用监听方式接收表单数据(req.on('data',(chunk)=&gt;{}))+req.on('end',()=&gt;{}))</p>
<div class="cnblogs_code"><img id="code_img_closed_043b3043-4518-4b58-ac66-05552e83c2ef" class="code_img_closed" src="https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt=""><img id="code_img_opened_043b3043-4518-4b58-ac66-05552e83c2ef" class="code_img_opened" style="display: none" src="https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="">
<div id="cnblogs_code_open_043b3043-4518-4b58-ac66-05552e83c2ef" class="cnblogs_code_hide">
<pre>let util_http=<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
   * 接口执行成功统一回复格式
   * @param {*} result 返回结果
   * @param {*} code 返回代码
   * @param {*} msg 返回消息
   </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
    async getPOSTRes(req){
       </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">new</span> Promise((resolve,reject)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
      let data </span>= ''<span style="color: rgba(0, 0, 0, 1)">;
      </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">2.注册data事件接收数据(每当收到一段表单提交的数据,该方法会执行一次)</span>
      req.on('data', <span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> (chunk) {
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> chunk 默认是一个二进制数据,和 data 拼接会自动 toString</span>
            data +=<span style="color: rgba(0, 0, 0, 1)"> chunk;
      });

      </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 3.当接收表单提交的数据完毕之后,就可以进一步处理了</span>
      <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">注册end事件,所有数据接收完成会执行一次该方法</span>
      req.on('end', <span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> () {
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">(1).对url进行解码(url会对中文进行编码)</span>
            data =<span style="color: rgba(0, 0, 0, 1)"> decodeURI(data);
            resolve(data)
      });
       })
    }
   
}

module.exports</span>=util_http</pre>
</div>
<span class="cnblogs_code_collapse">body表单数据接收</span></div>
<p>  接收参数时(包括接口中调用mysql接口时),均需要借助async,await关键字,将代码执行的控制权交给下一级中间件,待下一级中间件执行完成后,继续后续代码操作</p>
<p>另附mysql文件夹下的mysql配置文件和mysql操作文件</p>
<div class="cnblogs_code"><img id="code_img_closed_bceee368-489a-4a82-9163-1c2b6fef2f75" class="code_img_closed" src="https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt=""><img id="code_img_opened_bceee368-489a-4a82-9163-1c2b6fef2f75" class="code_img_opened" style="display: none" src="https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="">
<div id="cnblogs_code_open_bceee368-489a-4a82-9163-1c2b6fef2f75" class="cnblogs_code_hide">
<pre>const mysql = require('mysql'<span style="color: rgba(0, 0, 0, 1)">)

const connectdb</span>=()=&gt;<span style="color: rgba(0, 0, 0, 1)">{
let connection </span>=<span style="color: rgba(0, 0, 0, 1)"> mysql.createConnection({
    host   : </span>'localhost'<span style="color: rgba(0, 0, 0, 1)">,
    port   : </span>'3306'<span style="color: rgba(0, 0, 0, 1)">,
    user   : </span>'root'<span style="color: rgba(0, 0, 0, 1)">,
    password : </span>''<span style="color: rgba(0, 0, 0, 1)">,
    database : </span>'rehab'<span style="color: rgba(0, 0, 0, 1)">
})
</span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> connection;
}

module.exports</span>=connectdb;</pre>
</div>
<span class="cnblogs_code_collapse">mysql配置文件</span></div>
<div class="cnblogs_code"><img id="code_img_closed_d72bfe2e-31e2-4afb-bd10-11660bc10143" class="code_img_closed" src="https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt=""><img id="code_img_opened_d72bfe2e-31e2-4afb-bd10-11660bc10143" class="code_img_opened" style="display: none" src="https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="">
<div id="cnblogs_code_open_d72bfe2e-31e2-4afb-bd10-11660bc10143" class="cnblogs_code_hide">
<pre>const conn = require('./config/index'<span style="color: rgba(0, 0, 0, 1)">);
const connection </span>=<span style="color: rgba(0, 0, 0, 1)"> conn();

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 查询所有数据</span>
let selectAll = async(sql,callback)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
</span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> sqlQuery(sql)
}
let selectBy </span>= async(table,where,callback)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> _WHERE=''<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> var keys='';</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> var values='';</span>
    <span style="color: rgba(0, 0, 255, 1)">for</span>(<span style="color: rgba(0, 0, 255, 1)">var</span> k2 <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> where){
      _WHERE</span>+=k2+"='"+where+"' AND "<span style="color: rgba(0, 0, 0, 1)">;
      </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">_WHERE+= k2+"='"+where+"'";</span>
<span style="color: rgba(0, 0, 0, 1)">    }
    _WHERE</span>=_WHERE.slice(0,-5<span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> UPDATE user SET Password='321' WHERE UserId=12</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">update table set username='admin2',age='55'   where id="5";</span>
    <span style="color: rgba(0, 0, 255, 1)">var</span> sql="SELECT * FROM "+table+' WHERE '+<span style="color: rgba(0, 0, 0, 1)">_WHERE;
   </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> console.log(sql);</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> sqlQuery(sql)
}
</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 插入一条数据</span>
let insertData =async (table,datas,callback)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
</span><span style="color: rgba(0, 0, 255, 1)">var</span> fields=''<span style="color: rgba(0, 0, 0, 1)">;
</span><span style="color: rgba(0, 0, 255, 1)">var</span> values=''<span style="color: rgba(0, 0, 0, 1)">;
</span><span style="color: rgba(0, 0, 255, 1)">for</span>( <span style="color: rgba(0, 0, 255, 1)">var</span> k <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> datas){
      fields</span>+=k+','<span style="color: rgba(0, 0, 0, 1)">;
      values</span>=values+"'"+datas+"',"<span style="color: rgba(0, 0, 0, 1)">
}
fields</span>=fields.slice(0,-1<span style="color: rgba(0, 0, 0, 1)">);
values</span>=values.slice(0,-1<span style="color: rgba(0, 0, 0, 1)">);
</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> console.log(fields,values);</span>
<span style="color: rgba(0, 0, 255, 1)">var</span> sql="INSERT INTO "+table+'('+fields+') VALUES('+values+')'<span style="color: rgba(0, 0, 0, 1)">;
</span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> sqlQuery(sql)
}

</span><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* 更新一条数据
* @param {*} table 数据表名
* @param {*} sets 更新字段
* @param {*} where 限制条件
</span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
let updateData</span>=async <span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)">(table,sets,where){
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> _SETS=''<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> _WHERE=''<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> keys=''<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> values=''<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 0, 255, 1)">for</span>(<span style="color: rgba(0, 0, 255, 1)">var</span> k <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> sets){
      _SETS</span>+=k+"='"+sets+"',"<span style="color: rgba(0, 0, 0, 1)">;
    }
    _SETS</span>=_SETS.slice(0,-1<span style="color: rgba(0, 0, 0, 1)">);
    </span><span style="color: rgba(0, 0, 255, 1)">for</span>(<span style="color: rgba(0, 0, 255, 1)">var</span> k2 <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> where){
      _WHERE</span>+=k2+"='"+where+"' AND "<span style="color: rgba(0, 0, 0, 1)">;
      </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">_WHERE+= k2+"='"+where+"'";</span>
<span style="color: rgba(0, 0, 0, 1)">    }
    _WHERE</span>=_WHERE.slice(0,-5<span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> UPDATE user SET Password='321' WHERE UserId=12</span>
    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">update table set username='admin2',age='55'   where id="5";</span>
    <span style="color: rgba(0, 0, 255, 1)">var</span> sql="UPDATE "+table+' SET '+_SETS+' WHERE '+<span style="color: rgba(0, 0, 0, 1)">_WHERE;
   </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> console.log(sql);</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> sqlQuery(sql)
}

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 删除一条数据</span>
let deleteData=<span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)">(table,where,callback){
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> _WHERE=''<span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 0, 255, 1)">for</span>(<span style="color: rgba(0, 0, 255, 1)">var</span> k2 <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> where){
       _WHERE</span>+=k2+"='"+where+"' AND "<span style="color: rgba(0, 0, 0, 1)">;
      </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">_WHERE+= k2+"="+where;</span>
<span style="color: rgba(0, 0, 0, 1)">    }
    _WHERE</span>=_WHERE.slice(0,-5<span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> DELETEFROM user WHERE UserId=12注意UserId的数据类型要和数据库一致</span>
    <span style="color: rgba(0, 0, 255, 1)">var</span> sql="DELETEFROM "+table+' WHERE '+<span style="color: rgba(0, 0, 0, 1)">_WHERE;
   </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> connection.query(sql,callback);</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> sqlQuery(sql)
}

let sqlQuery</span>=<span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)">(sql){
</span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">new</span> Promise((resolve,reject)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    connection.query(sql,(err,result)</span>=&gt;<span style="color: rgba(0, 0, 0, 1)">{
      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)">(err){
          console.log(</span>'错误信息-'<span style="color: rgba(0, 0, 0, 1)">,err.sqlMessage);
          let errNews </span>=<span style="color: rgba(0, 0, 0, 1)"> err.sqlMessage;
          reject(errNews)
      } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">{
      resolve(result)
      }
    })
})
}
module.exports </span>=<span style="color: rgba(0, 0, 0, 1)"> {
selectAll,
selectBy,
insertData,
deleteData,
updateData,
}</span></pre>
</div>
<span class="cnblogs_code_collapse">mysql操作文件</span></div>
<p>&nbsp;</p>
<p><strong>VUE操作(接口调用操作)</strong></p>
<p>1、Vue-cli 3.0搭建项目,配置package.json项目依赖,添加vue.js文件,配置vue文件路由,main.js的组件引用操作省略</p>
<p>2、测试文件</p>
<div class="cnblogs_code"><img id="code_img_closed_8482a892-999a-4f04-bd9c-80fa6d80bfd3" class="code_img_closed" src="https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt=""><img id="code_img_opened_8482a892-999a-4f04-bd9c-80fa6d80bfd3" class="code_img_opened" style="display: none" src="https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="">
<div id="cnblogs_code_open_8482a892-999a-4f04-bd9c-80fa6d80bfd3" class="cnblogs_code_hide">
<pre>&lt;template&gt;
&lt;div class="api"&gt;
    &lt;div class="api-item"&gt;
      &lt;van-button type="default" @click="getTest"&gt;get test&lt;/van-button&gt;
    &lt;/div&gt;
    &lt;div class="api-item"&gt;
      &lt;van-field v-model="name.add" placeholder="请输入name" /&gt;
      &lt;van-button type="default" @click="addTest"&gt;add test&lt;/van-button&gt;
    &lt;/div&gt;
    &lt;div class="api-item"&gt;
      &lt;van-field v-model="name.update_set" placeholder="请输入更改值" /&gt;
      &lt;van-field v-model="name.update_where" placeholder="请输入初始值" /&gt;
      &lt;van-button type="default" @click="updateTest"&gt;update test&lt;/van-button&gt;
    &lt;/div&gt;
    &lt;div class="api-item"&gt;
      &lt;van-field v-model="name.delete" placeholder="请输入删除值" /&gt;
      &lt;van-button type="default" @click="deleteTest"&gt;<span style="color: rgba(0, 0, 255, 1)">delete</span> test&lt;/van-button&gt;
    &lt;/div&gt;
    &lt;div class="api-item api-result"&gt;
      &lt;p&gt;result:&lt;/p&gt;
      &lt;p&gt;code:{{result.code}}&lt;/p&gt;
      &lt;p&gt;msg:{{result.msg}}&lt;/p&gt;
      &lt;p&gt;result:{{result.result}}&lt;/p&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;<span style="color: rgba(0, 0, 0, 1)">
    import {api} from </span>"../../api/server"<span style="color: rgba(0, 0, 0, 1)">;

    export </span><span style="color: rgba(0, 0, 255, 1)">default</span><span style="color: rgba(0, 0, 0, 1)"> {
      name: </span>"apitest"<span style="color: rgba(0, 0, 0, 1)">,
      data(){
            </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)">{
                openid:</span>'28d91cb4-28a6-4110-b401-a6ca03cddf27'<span style="color: rgba(0, 0, 0, 1)">,
                result:</span>''<span style="color: rgba(0, 0, 0, 1)">,
                name:{
                  add:</span>'22'<span style="color: rgba(0, 0, 0, 1)">,
                  update_set:</span>'44'<span style="color: rgba(0, 0, 0, 1)">,
                  update_where:</span>'33'<span style="color: rgba(0, 0, 0, 1)">,
                  </span><span style="color: rgba(0, 0, 255, 1)">delete</span>:'2233'<span style="color: rgba(0, 0, 0, 1)">
                },
                msg:</span>''<span style="color: rgba(0, 0, 0, 1)">
            }
      },
      methods:{
            getTest(){
                let params</span>=<span style="color: rgba(0, 0, 0, 1)">{
                  table:</span>'test'<span style="color: rgba(0, 0, 0, 1)">
                }
                let that</span>=<span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">;
                api.get(params).then(res</span>=&gt;<span style="color: rgba(0, 0, 0, 1)">{
                  console.log(</span>'res'<span style="color: rgba(0, 0, 0, 1)">,res)
                  that.result</span>=<span style="color: rgba(0, 0, 0, 1)">res
                }).</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(err=&gt;<span style="color: rgba(0, 0, 0, 1)">{
                  console.log(</span>'err'<span style="color: rgba(0, 0, 0, 1)">,err)
                  that.result</span>=<span style="color: rgba(0, 0, 0, 1)">err
                })
            },
            addTest(){
                </span><span style="color: rgba(0, 0, 255, 1)">if</span>(<span style="color: rgba(0, 0, 255, 1)">this</span>.name.add==''<span style="color: rgba(0, 0, 0, 1)">){
                  </span><span style="color: rgba(0, 0, 255, 1)">this</span>.Toast('请输入name'<span style="color: rgba(0, 0, 0, 1)">);
                  </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">
                }
                let params</span>=<span style="color: rgba(0, 0, 0, 1)"> {
                  table: </span>'test'<span style="color: rgba(0, 0, 0, 1)">,
                  params: {
                        id: </span><span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.util.randomNum(),
                        name: </span><span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.name.add
                  }
                }
                let that</span>=<span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">;
                api.add(params).then(res</span>=&gt;<span style="color: rgba(0, 0, 0, 1)">{
                  console.log(</span>'res'<span style="color: rgba(0, 0, 0, 1)">,res)
                  that.result</span>=<span style="color: rgba(0, 0, 0, 1)">res
                }).</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(err=&gt;<span style="color: rgba(0, 0, 0, 1)">{
                  console.log(</span>'err'<span style="color: rgba(0, 0, 0, 1)">,err)
                  that.result</span>=<span style="color: rgba(0, 0, 0, 1)">err
                })
            },
            updateTest(){
                </span><span style="color: rgba(0, 0, 255, 1)">if</span>(<span style="color: rgba(0, 0, 255, 1)">this</span>.name.update_where==''||<span style="color: rgba(0, 0, 255, 1)">this</span>.name.update_set==''<span style="color: rgba(0, 0, 0, 1)">){
                  </span><span style="color: rgba(0, 0, 255, 1)">this</span>.Toast('请输入name'<span style="color: rgba(0, 0, 0, 1)">);
                  </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">
                }
                let params</span>=<span style="color: rgba(0, 0, 0, 1)"> {
                  table: </span>'test'<span style="color: rgba(0, 0, 0, 1)">,
                  sets: {
                        name:</span><span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.name.update_set
                  },
                  where: {
                        name:</span><span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.name.update_where
                  }
                }
                </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> let params={</span>
                <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   id:'11',</span>
                <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   name:'22'</span>
                <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> }</span>
                let that=<span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">;
                api.update(params).then(res</span>=&gt;<span style="color: rgba(0, 0, 0, 1)">{
                  console.log(</span>'res'<span style="color: rgba(0, 0, 0, 1)">,res)
                  that.result</span>=<span style="color: rgba(0, 0, 0, 1)">res
                }).</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(err=&gt;<span style="color: rgba(0, 0, 0, 1)">{
                  console.log(</span>'err'<span style="color: rgba(0, 0, 0, 1)">,err)
                  that.result</span>=<span style="color: rgba(0, 0, 0, 1)">err
                })
            },
            deleteTest(){
                </span><span style="color: rgba(0, 0, 255, 1)">if</span>(<span style="color: rgba(0, 0, 255, 1)">this</span>.name.update_where==''||<span style="color: rgba(0, 0, 255, 1)">this</span>.name.update_set==''<span style="color: rgba(0, 0, 0, 1)">){
                  </span><span style="color: rgba(0, 0, 255, 1)">this</span>.Toast('请输入name'<span style="color: rgba(0, 0, 0, 1)">);
                  </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">
                }
                let params</span>=<span style="color: rgba(0, 0, 0, 1)"> {
                  table: </span>'test'<span style="color: rgba(0, 0, 0, 1)">,
                  where: {
                        name:</span><span style="color: rgba(0, 0, 255, 1)">this</span>.name.<span style="color: rgba(0, 0, 255, 1)">delete</span><span style="color: rgba(0, 0, 0, 1)">
                  }
                }
                </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> let params={</span>
                <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   id:'11',</span>
                <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">   name:'22'</span>
                <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> }</span>
                let that=<span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">;
                api.</span><span style="color: rgba(0, 0, 255, 1)">delete</span>(params).then(res=&gt;<span style="color: rgba(0, 0, 0, 1)">{
                  console.log(</span>'res'<span style="color: rgba(0, 0, 0, 1)">,res)
                  that.result</span>=<span style="color: rgba(0, 0, 0, 1)">res
                }).</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(err=&gt;<span style="color: rgba(0, 0, 0, 1)">{
                  console.log(</span>'err'<span style="color: rgba(0, 0, 0, 1)">,err)
                  that.result</span>=<span style="color: rgba(0, 0, 0, 1)">err
                })
            },
      }
    }
</span>&lt;/script&gt;

&lt;style lang="less" scoped&gt;<span style="color: rgba(0, 0, 0, 1)">
.api{
    text</span>-<span style="color: rgba(0, 0, 0, 1)">align: left;
    background</span>-<span style="color: rgba(0, 0, 0, 1)">color: #ffffff;
    .api</span>-<span style="color: rgba(0, 0, 0, 1)">item{
      margin: 8px;
    }
}
</span>&lt;/style&gt;</pre>
</div>
<span class="cnblogs_code_collapse">vue测试页</span></div>
<p>&nbsp;3、api接口</p>
<div class="cnblogs_code"><img id="code_img_closed_30d46f70-534f-46c6-b6f1-d31422a7361f" class="code_img_closed" src="https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt=""><img id="code_img_opened_30d46f70-534f-46c6-b6f1-d31422a7361f" class="code_img_opened" style="display: none" src="https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="">
<div id="cnblogs_code_open_30d46f70-534f-46c6-b6f1-d31422a7361f" class="cnblogs_code_hide">
<pre>import axios from 'axios'<span style="color: rgba(0, 0, 0, 1)">;
const server </span>= 'http://localhost:3000'<span style="color: rgba(0, 0, 0, 1)">;

exportconst api</span>=<span style="color: rgba(0, 0, 0, 1)">{
    get(params){
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> axios.get(server + '/mysql/findAll'<span style="color: rgba(0, 0, 0, 1)">, {params});
    },
    add(params){
      let headers </span>= {'Content-Type': 'multipart/form-data'<span style="color: rgba(0, 0, 0, 1)">}
       </span><span style="color: rgba(0, 0, 255, 1)">return</span> axios.post(server + '/mysql/add'<span style="color: rgba(0, 0, 0, 1)">, params, {headers});
    },
    update(params){
         let headers </span>= {'Content-Type': 'multipart/form-data'<span style="color: rgba(0, 0, 0, 1)">}
       </span><span style="color: rgba(0, 0, 255, 1)">return</span> axios.put(server + '/mysql/update'<span style="color: rgba(0, 0, 0, 1)">, params,{headers});
    },
    </span><span style="color: rgba(0, 0, 255, 1)">delete</span><span style="color: rgba(0, 0, 0, 1)">(params){
      let headers </span>= {'Content-Type': 'multipart/form-data'<span style="color: rgba(0, 0, 0, 1)">}
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> axios.<span style="color: rgba(0, 0, 255, 1)">delete</span>(server + '/mysql/delete'<span style="color: rgba(0, 0, 0, 1)">, {data:params},{headers});
    },
}</span></pre>
</div>
<span class="cnblogs_code_collapse">vue api接口</span></div>
<p>&gt; 示例中使用的是axios组件调用的api接口</p>
<p>&gt; params接口参数形式说明</p>
<p>  &gt;&gt; get接口参数需要使用{}包裹,如{params}</p>
<p>  &gt;&gt; post\put接口直接添加params参数</p>
<p>  &gt;&gt; delete接口需加上'data'说明,如{data:params}</p>
<p>&gt;headers</p>
<p>  &gt;&gt; post\put\delete三种方式需要添加请求头header设置 <span style="color: rgba(69, 131, 131, 1)">headers = {<span style="color: rgba(0, 128, 0, 1); font-weight: bold">'Content-Type': <span style="color: rgba(0, 128, 0, 1); font-weight: bold">'multipart/form-data'}</span></span></span></p>
<p>  在node.js中接收方式为ctx.request.body</p>
<p>  &gt;&gt; get方式请求不需要加请求头,在node.js中接收方式为ctx.request.query</p>
<p>  &gt;&gt; put\delete 请求方式在发送请求前会先发送预请求命令,请求方式为OPTIONS,这时只需要在node.js中正常返回,不需要做任何处理</p>
<p>&nbsp;</p>
<p>最后,展示几种接口在postman中的调用方式</p>
<p><img src="https://img2018.cnblogs.com/blog/451237/201910/451237-20191026201710176-1373458847.png" alt="" width="572" height="200"></p>
<p><img src="https://img2018.cnblogs.com/blog/451237/201910/451237-20191026201956331-557615684.png" alt="" width="821" height="200"></p>
<p>&nbsp;<img src="https://img2018.cnblogs.com/blog/451237/201910/451237-20191026202030613-2055896920.png" alt="" width="816" height="200"></p>
<p><img src="https://img2018.cnblogs.com/blog/451237/201910/451237-20191026202104681-1167070511.png" alt="" width="812" height="200"></p><br><br>
来源:https://www.cnblogs.com/eye-like/p/11743744.html
頁: [1]
查看完整版本: node.js 接口调用示例