前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Node.js 模拟本地接口测试环境以及简单的代理转发服务

Node.js 模拟本地接口测试环境以及简单的代理转发服务

作者头像
老猫-Leo
发布2023-12-11 21:02:17
3240
发布2023-12-11 21:02:17
举报
文章被收录于专栏:前端大全前端大全

为方便测试小哥调试,用 Node.js 模拟了一些简单的接口测试业务场景。

Koa 简单模拟服务器

代码语言:javascript
复制
const Koa = require('koa');
const KoaBodyParser = require('koa-bodyparser');
const KoaRouter = require('koa-router');

const app = new Koa();
const router = new KoaRouter();

app.use(KoaBodyParser());

app.use(async (ctx, next) => {
  const { path, method } = ctx;
  console.log({ ctx });
  // ctx.set('Access-Control-Allow-Origin', '*');
  // ctx.set('Content-Type', 'application/json');
  let status = Number(path?.split('/')[1] ?? 200) || 400;
  ctx.status = status;
  ctx.body = {
    path,
    url: ctx.request.url,
    status,
    method,
    data: {
      body: ctx.request.body,
      query: ctx.request.query,
      querystring: ctx.request.querystring
    },
    msg: `${method}[${path}](请求完成-${status})`
  };
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, 2000);
  });
  await next();
});

// const cors = require('koa-cors');
// app.use(cors());

// router.post('/post', async (ctx, next) => {
//   const { path, method } = ctx;
//   let data = {
//     body: ctx.request.body,
//     query: ctx.request.query,
//     querystring: ctx.request.querystring
//   };
//   ctx.body = {
//     status: 200,
//     path,
//     method,
//     data,
//     msg: 'POST test'
//   };
//   await next();
// });
// router.get('/hello/:name', async (ctx, next) => {
//   let name = ctx.params.name;
//   const { path, method } = ctx;
//   let data = {
//     body: ctx.request.body,
//     query: ctx.request.query,
//     querystring: ctx.request.querystring
//   };
//   ctx.body = {
//     status: 200,
//     path,
//     method,
//     data,
//     msg: `get ${name}`
//   };
//   await next();
// });
// app.use(router.routes());

app.on('error', (err) => {
  console.log('server error', err);
});

app.listen(666);

console.log('app started at port 666...');

Express 简单模拟服务器

代码语言:javascript
复制
const express = require('express');
const bodyParser = require('body-parser');

const app = express();

app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
});

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());

app.post('/post/:name', function (req, res) {
  res.status(200).send({
    status: 200,
    path: req.path,
    url: req.url,
    method: req.method,
    data: {
      body: req.body,
      query: req.query,
      querystring: req.originalUrl.split('?')[1],
      params: req.params
    },
    msg: 'POST test'
  });
});

const server = app.listen(888, function () {
  let host = server.address().address;
  let port = server.address().port;

  console.log('server:http://localhost:%s', port);
});

Koa+Request 代理转发请求

代码语言:javascript
复制
const request = require('request');
const Koa = require('koa');
const KoaRouter = require('koa-router');
const cors = require('koa-cors');

const app = new Koa();
const router = new KoaRouter();
app.use(cors());

router.get('/get', async (ctx, next) => {
  return new Promise((resolve) =>
    request(
      {
        url: 'http://localhost:666/hello/world?q=123',
        method: 'GET',
        json: true,
        headers: {
          'Content-Type': 'application/json'
        },
        body: ctx.request.body
      },
      function (error, response, body) {
        ctx.status = response.statusCode;
        if (error) {
          console.log('---------------ERROR----------------');
          console.log(error);
          ctx.body = error;
          resolve(next());
          console.log('---------------ERROR----------------');
        } else {
          console.log('---------------SUCCESS----------------');
          console.log(body);
          ctx.body = body;
          resolve(next());
          console.log('---------------SUCCESS----------------');
        }
      }
    )
  );
});

app.use(router.routes());

app.on('error', (err) => {
  console.log('server error', err);
});

app.listen(10010);
console.log('proxy started at port 10010...');

Express+Request 代理转发请求

代码语言:javascript
复制
const request = require('request');
const express = require('express');

const app = express();

app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
});

app.get('/get', (req, res) => {
  request(
    {
      url: 'http://localhost:666/hello/world?q=123',
      method: 'GET',
      json: true,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(req.body)
    },
    function (error, response, body) {
      if (error) {
        console.log('---------------ERROR----------------');
        console.log(error);
        res.status(response.statusCode).send(error);
        res.end();
        console.log('---------------ERROR----------------');
      } else {
        console.log('---------------SUCCESS----------------');
        console.log(body);
        res.status(response.statusCode).send(body);
        res.end();
        console.log('---------------SUCCESS----------------');
      }
    }
  );
});

app.listen(10086);
console.log('proxy started at port 10086...');
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-06-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Koa 简单模拟服务器
  • Express 简单模拟服务器
  • Koa+Request 代理转发请求
  • Express+Request 代理转发请求
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档