首页 » 前端 » NodeJS » 正文

用 node 创建一个测试用的 web 服务并代理转发接口调用

发布者:站点默认
2015/01/23 浏览数(2,025) 分类:NodeJS 用 node 创建一个测试用的 web 服务并代理转发接口调用已关闭评论

package.json

{
  "scripts": {
    "serve": "node dev-server.js"
  },
  "devDependencies": {
    "chalk": "^4.1.2",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "http-proxy-middleware": "^2.0.6",
    "morgan": "^1.10.0",
    "st": "^3.0.0"
  },
  "license": "ISC"
}

dev-server.js

const express = require('express');
const morgan = require('morgan');
const st = require('st');
const { createProxyMiddleware } = require('http-proxy-middleware');
const chalk = require('chalk');
const app = express();
require('dotenv').config();

// PORT:0 可让系统自己选择可用端口
const PORT = 3000;
const HOST = 'localhost';

// 控制台输出
app.use(
  morgan('dev', {
    skip: function (req, res) {
      return res.statusCode < 400;
    },
  })
);

app.use(
  '/java-api',
  createProxyMiddleware({
    target: process.env.API_BASE_URL,
    changeOrigin: true,
    pathRewrite: {
      // "^/javaApi": "",
    },
  })
);
app.use(
  '/node-api',
  createProxyMiddleware({
    target: process.env.API_BASE_URL,
    changeOrigin: true,
    pathRewrite: {
      // "^/api": "",
    },
  })
);

app.use(
  st({
    path: '.',
    cache: false,
  })
);

app.listen(PORT, HOST, () => {
  console.log('Starting Proxy at ' + chalk.green(`http://${HOST}:${PORT}`));
});
点击返回顶部
  1. 留言
  2. 联系方式