node工具之http-proxy-middleware

简介

一个轻松的配置代理服务器的中间件,让Node.js代理变得简单

url路径

         foo://example.com:8042/over/there?name=ferret#nose
         \_/   \______________/\_________/ \_________/ \__/
          |           |            |            |        |
       scheme     authority       path        query   fragment

基本使用

var express = require('express');
var proxy = require('http-proxy-middleware');

var app = express();

app.use(
  '/api',
  proxy({ target: 'http://www.example.org', changeOrigin: true })
);
app.listen(3000);

两种形式

var apiProxy = proxy('/api', { target: 'http://www.example.org' });
//同样效果
var apiProxy = proxy('http://www.example.org/api');

配置

var options = {
  target: 'http://www.example.org', // 目标
  changeOrigin: true, // 虚拟站点必须
  ws: true, // 代理websocket
  pathRewrite: {
    '^/api/old-path': '/api/new-path', // 重写路径
  },
  router: {
    // when request.headers.host == 'dev.localhost:3000',
    // override target 'http://www.example.org' to 'http://localhost:8000'
    'dev.localhost:3000': 'http://localhost:8000'
  }
};

实际使用

const express = require("express");
const next = require("next");
const dev = process.env.NODE_ENV !== "production"; //判断是否是开发环境
const app = next({ dev });
const handle = app.getRequestHandler();
const compression = require("compression");
const port = parseInt(process.env.PORT, 10) || 6776;
const proxy = require("http-proxy-middleware");

const proxyOption = {
  target: "http://127.0.0.1:6688",
  pathRewrite: {
    "^/api/": "/" // 重写请求,api/解析为/
  },
  changeOrigoin: true
};

app
  .prepare()
  .then(() => {
    const server = express();

    if (dev) {
      server.use("/api/*", proxy(proxyOption));
    }

    if (!dev) {
      server.use(compression()); //gzip
    }

    server.get("/", (req, res) => app.render(req, res, "/home"));
    server.get("/home", (req, res) => app.render(req, res, "/home"));
    server.get("/books", (req, res) => app.render(req, res, "/books"));
    server.get("/articles", (req, res) => app.render(req, res, "/articles"));
    server.get("/login", (req, res) => app.render(req, res, "/login"));
    server.get("/markdown", (req, res) => app.render(req, res, "/markdown"));
    server.get("/books", (req, res) => app.render(req, res, "/books"));
    server.get("/write", (req, res) => app.render(req, res, "/write"));
    server.get("/book/:currentBookId", (req, res) =>
      app.render(req, res, "/book/[currentBookId]", { currentBookId: req.params.currentBookId })
    );
    server.get("/article/:curArticleId", (req, res) =>
      app.render(req, res, "/article/[curArticleId]", { curArticleId: req.params.curArticleId })
    );
    server.all("*", (req, res) => handle(req, res));

    server.listen(port, err => {
      if (err) throw err;
      else console.log(`http start at ===> http://localhost:${port}`);
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });

doc

原文地址:https://www.cnblogs.com/mybilibili/p/11780960.html

时间: 2024-08-09 20:47:16

node工具之http-proxy-middleware的相关文章

[node 工具] 用 Node.js 将 bugzilla 上的 bug 列表导入到 excel 表格在线版本之一(server 端)

之前写了个 用 Node.js 将 bugzilla 上的 bug 列表导入到 excel 表格里 的 cli 工具虽然可以用,但考虑到一下几点,总觉得需要再做点什么. 界面简陋,我那截图上是在 VSCode 下的 git bash 里使用的,看起来倒还好一些.如果是在 CMD 下使用,不忍直视. 需要使用命令的方式启动,URL 地址还需要添加双引号,体验不好. 需要自行安装 nodejs 环境 因此我将这个工具做成了在线的版本,只要复制个 URL,点击开始,傻瓜操作,多人使用. 1 var e

node工具之nodemon

nodemon nodemon是一种工具,可以自动检测到目录中的文件更改时通过重新启动应用程序来调试基于node.js的应用程序. 安装 npm install -g nodemon //或 npm install --save-dev nodemon 使用 nodemon ./main.js // 启动node服务 nodemon ./main.js localhost 6677 // 在本地6677端口启动node服务 "start": "ts-node -r tscon

node工具之pm2

pm2 PM2是带有内置负载平衡器的Node.js应用程序的生产过程管理器.它使您可以使应用程序永远保持活动状态,无需停机即可重新加载它们,并简化常见的系统管理任务. 安装 npm install pm2 -g 常用命令 pm2 start app.js 开启进程 pm2 list 所有进程 pm2 stop <app_name|id|'all'|json_conf> / all 停止 pm2 restart <app_name|id|'all'|json_conf> 重启 pm2

NTVS:把Visual Studio变成Node.js IDE 的工具

NTVS(Node.js Tools for Visual Studio) 运行于VS2012或者VS2013.一些node.js的爱好者已经从PTVS(Python Tools for Visual Studio)转向并开始为VS做些node工具.同时,PTVS团队也在node.js整合上下功夫,于是他们都专注于NTVS使之成为一个社区项目.NTVS是由给你带来PTVS的相同团队开发的,并且得到了来自Red Gate的Bart Read(他开发了Node Packaged Modules图形用

Connect is a middleware layer for Node.js

Connect is a middleware layer for Node.js   http://senchalabs.github.com/connect Connect Connect is an extensible HTTP server framework for node using "plugins" known as middleware. var connect = require('connect') var http = require('http') var

46 puppet master-agent模型、运维工具介绍及pxe环境的实现、cobbler简单实现、CentOS7 cobbler

01 puppet master-agent模型 配置环境 node1 192.168.1.131 CentOS7.2 node2 192.168.1.132 CentOS7.2 node3 192.168.1.133 CentOS7.2 node4 192.168.1.134 CentOS7.2 1.agent节点扩展为master节点 [[email protected] ~]# yum -y install puppet-server-3.8.4-1.el7.noarch.rpm [[em

K8s之kubectl命令行工具常用命令

kubectl管理 Kubectl是管理k8s集群的命令行工具,通过生成的json格式传递给apiserver进行创建.查看.管理的操作 注意:此处需要用到我们之前部署的K8s多节点的部署环境,如果还未部署的可以参考我的上篇文章:https://blog.csdn.net/JarryZho/article/details/104212822 常用命令行: `查看帮助命令` [[email protected] ~]# kubectl --help kubectl controls the Kub

Node教程——API接口开发(MangoDB+Express)

git源码 说明:源码已经全部上传到github,仓库地址: https://github.com/BM-laoli/Node-api-Design 一.大纲 大纲: 关于架构, 首先我们的有一个app.js这个就是根路由起点,用来最初的打入口 它的功能有: 1.1 引入模块创建基础的网站服务器, 1.2 导入bodyPasser,过滤还有处理我们的post请求 1.3 导入数据库连接 1.4 把路由开放出去 再来一个main.js它在我的route文件夹下, 2.1 什么需啊哟再这里做二次拦截

工具函数(二)

测试操作 在jQuery中,数据有着各种类型和状态.有时,我们希望能通过判断数据的类型和状态做相应的操作.jQuery提供了五组测试用的工具函数. 测试工具函数 函数名 说明 $.isArray(obj) 判断是否为数组对象,是返回true $.isFunction(obj) 判断是否为函数,是返回true $.isEmptyObject(obj) 判断是否为空对象,是返回true $.isPlainObject(obj) 判断是否为纯粹对象,是返回true $.contains(obj) 判断