node+express请求代理:http-proxy-middleware模块

前言

现在很多用node作为代理服务器处理一些接口请求,node管理静态资源,而数据API的请求则转发出去。这样也可以解决跨域的问题。

http-proxy-middleware

官方文档:http-proxy-middleware

安装

# npm安装时可能报错,所以使用cnpm
cnpm install http-proxy-middleware --save-dev

简单使用

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)
 
// http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar
  • 注意:请求的接口被转发到新地址,在浏览器network中是看不到的。

实例:

接下来实例会创建一个本地服务 http://localhost:3000来做静态资源渲染,其中对http://localhost:3000/api/*下的请求都转发到http://localhost:8080/*完成。

test-proxy.js :用于localhost:3000服务
var express = require('express');
var proxy = require('http-proxy-middleware');
var app= express();
var options = {
  target: 'http://www.example.org', //转发到的地址
  changeOrigin: true, // needed for virtual hosted sites
  ws: true, // 代理websocket
  pathRewrite: {
    '^/api': '', // rewrite path
  },
  router: {
    // 当请求localhost:3000/api时,会转发到http://localhost:8080,
    'localhost:3000/api': 'http://localhost:8080'
  }
}
var exampleProxy = proxy(options)
app.use('/api', exampleProxy)
app.get('/index.html', function(req,res){
     res.sendFile(__dirname+'/public/index.html');
});
app.listen(3000,function(){
	console.log('服务启动到3000端口')
})
3000端口服务/public/下的index.html
<!DOCTYPE html>
<html>
<head>
    <title>首页</title>
    <meta charset="utf-8">
    <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
 	<script type="text/javascript">
        $(function(){
            var contextPath = 'http://localhost:3000';
             $.ajax({
                    type:'get',
                    data:'click',
                    url:contextPath+'/api/hello',
                    success:function(data){
                        console.log(data);
                    },
                    error:function(data){
                        console.log(data);
                    }
			})
        })
    </script>
</body>
</html>
test-8080.js - 用于8080服务
var express = require('express');
var app = express();
app.use(express.static('public'));
var server = app.listen(8080,function(){
    var host = server.address().address;
    var port = server.address().port;
    console.log('应用实例,访问地址为 http://%s:%s',host,port);
})

app.get('/hello', function(req,res){
    let data = {}
    data["name"] = "lucy";
    data["age"] = "23";
    res.send(data);
});

如上:请求localhost:3000会经历如下过程

  • 浏览器请求localhost:3000
  • 返回index.html。浏览器发出ajax请求http://localhost:3000/api/hello
  • 3000服务接收到http://localhost:3000/api/hello请求,转发到http://localhost:8080/hello
  • 8080服务接收到http://localhost:8080/hello,返回相应的数据

注意:

  • 浏览器的Network中看到的请求头仍然是:Request URL: http://localhost:3000/api/hello。也就是说,代理转发在前台是追踪不到的。
发布了114 篇原创文章 · 获赞 146 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/Sophie_U/article/details/86140800