简介

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

url路径

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

基本使用

  1. var express = require('express');
  2. var proxy = require('http-proxy-middleware');
  3. var app = express();
  4. app.use(
  5. '/api',
  6. proxy({ target: 'http://www.example.org', changeOrigin: true })
  7. );
  8. app.listen(3000);

两种形式

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

配置

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

实际使用

  1. const express = require("express");
  2. const next = require("next");
  3. const dev = process.env.NODE_ENV !== "production"; //判断是否是开发环境
  4. const app = next({ dev });
  5. const handle = app.getRequestHandler();
  6. const compression = require("compression");
  7. const port = parseInt(process.env.PORT, 10) || 6776;
  8. const proxy = require("http-proxy-middleware");
  9. const proxyOption = {
  10. target: "http://127.0.0.1:6688",
  11. pathRewrite: {
  12. "^/api/": "/" // 重写请求,api/解析为/
  13. },
  14. changeOrigoin: true
  15. };
  16. app
  17. .prepare()
  18. .then(() => {
  19. const server = express();
  20. if (dev) {
  21. server.use("/api/*", proxy(proxyOption));
  22. }
  23. if (!dev) {
  24. server.use(compression()); //gzip
  25. }
  26. server.get("/", (req, res) => app.render(req, res, "/home"));
  27. server.get("/home", (req, res) => app.render(req, res, "/home"));
  28. server.get("/books", (req, res) => app.render(req, res, "/books"));
  29. server.get("/articles", (req, res) => app.render(req, res, "/articles"));
  30. server.get("/login", (req, res) => app.render(req, res, "/login"));
  31. server.get("/markdown", (req, res) => app.render(req, res, "/markdown"));
  32. server.get("/books", (req, res) => app.render(req, res, "/books"));
  33. server.get("/write", (req, res) => app.render(req, res, "/write"));
  34. server.get("/book/:currentBookId", (req, res) =>
  35. app.render(req, res, "/book/[currentBookId]", { currentBookId: req.params.currentBookId })
  36. );
  37. server.get("/article/:curArticleId", (req, res) =>
  38. app.render(req, res, "/article/[curArticleId]", { curArticleId: req.params.curArticleId })
  39. );
  40. server.all("*", (req, res) => handle(req, res));
  41. server.listen(port, err => {
  42. if (err) throw err;
  43. else console.log(`http start at ===> http://localhost:${port}`);
  44. });
  45. })
  46. .catch(ex => {
  47. console.error(ex.stack);
  48. process.exit(1);
  49. });

doc

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

  1. node工具是是什么东西

    Node到底是个啥? Node是一个服务器端JavaScript解释器,可是真的以为JavaScript不错的同学学习Node就能轻松拿下,那么你就错了,总结:水深不深我还不知道,不过确实不浅 最近写 ...

  2. [Node] Setup an Nginx Proxy for a Node.js App

    Learn how to setup an Nginx proxy server that sits in front of a Node.js app. You can use a proxy to ...

  3. node工具之nodemon

    nodemon nodemon是一种工具,可以自动检测到目录中的文件更改时通过重新启动应用程序来调试基于node.js的应用程序. 安装 npm install -g nodemon //或 npm ...

  4. node工具之node-ip

    node-ip node.js用来获取id地址的工具 use var ip = require('ip'); ip.address() // my ip address ip.isEqual('::1 ...

  5. node工具--express

    //使用supervisor  Connect是基于HTTP米快创建的:Express则是基于Connect上创建的: 绝大多数web服务器和浏览器之间的任务是通过url和method完成的,两者的组 ...

  6. node工具--connect

    HTTP构建一个网站: var http = require('http'); var fs = require('fs'); var server = http.createServer(funct ...

  7. node工具之pm2

    pm2 PM2是带有内置负载平衡器的Node.js应用程序的生产过程管理器.它使您可以使应用程序永远保持活动状态,无需停机即可重新加载它们,并简化常见的系统管理任务. 安装 npm install p ...

  8. Connect is a middleware layer for Node.js

     Connect is a middleware layer for Node.js   http://senchalabs.github.com/connect Connect Connect is ...

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

    NTVS(Node.js Tools for Visual Studio) 运行于VS2012或者VS2013.一些node.js的爱好者已经从PTVS(Python Tools for Visual ...

随机推荐

  1. 系统芯片 SoC

    SoC的定义多种多样,由于其内涵丰富.应用范围广,很难给出准确定义.一般说来, SoC称为系统级芯片,也有称片上系统,意指它是一个产品,是一个有专用目标的集成电路,其中包含完整系统并有嵌入软件的全部内 ...

  2. This sample is for changing from “float64” to “int” for values did unmarshal using map[string]interface{}. When it did unmarshal using map[string]interface{}, a number with “int” was changed to “floa

    This sample is for changing from “float64” to “int” for values did unmarshal using map[string]interf ...

  3. Linux配置Key,禁止root实现免密码登陆

    前言:        我所理解的是Key登陆认证方式,其实就是拿私钥去解密公钥,私钥需要自己妥善保管,公钥可以随意公开. 废话少说,准备2台服务器,Server1:192.168.1.1   Serv ...

  4. 阶段3 3.SpringMVC·_06.异常处理及拦截器_3 SpringMVC异常处理之异常处理代码编写

    分三步 新建exception的包.然后添加SysException类 一般写异常都继承.Exception 定义Messgae属性,生成get和set 生成带参数的构造方法 选中异常的代码 Ctrl ...

  5. IntelliJ IDEA 2019 注册码 (激活码) 有效期至2100年

    IntelliJ IDEA 2019 注册码 (激活码) 有效期至2100年 本人使用的IDEA是最新版:IntelliJ IDEA 2018.3.3 x64 (IntelliJ IDEA官网下载地址 ...

  6. CnPack开发包基础库

    unit CnCommon; {* |<PRE> ===================================================================== ...

  7. Delphi动态创建菜单

    在程序运行中动态创建菜单,主要使用TMeunItem类,所有菜单的条目都是TMenuItem的一个实例. 打开Delphi7集成开发环境,在默认新建工程里,放置一个Button1按钮和MainMenu ...

  8. CentOS下安装完php外网无法访问的问题

    1. cd /etc/selinux/ vim config SELINUX=disabled 2.通过界面关闭防火墙

  9. super()使用方法

    super()使用方法   我们经常在类的继承当中使用super(), 来调用父类中的方法.例如下面: class A: def func(self): print('OldBoy') class B ...

  10. ubuntu中配置jdk1.8

    方法/步骤   1 首先,百度搜索jdk,选择第一个,网站是Oracle Jdk.点击进去 步骤阅读 2 点击Download,到官网下载linux版本的jdk.选择自己对应的操作系统及32或64位版 ...