browser-sync + http-proxy-middleware 配置代理跨域

express

在前端写代理文件

 1 /**
 2  * Module dependencies.
 3  */
 4 var browserSync = require('browser-sync').create()
 5 var proxy = require('http-proxy-middleware') // require('http-proxy-middleware');
 6 
 7 /**
 8  * Configure proxy middleware
 9  */
10 // 这里配置当以 /api 请求的时候,转发到 http://127.0.0.1:5000
11 // origin 原本的,源路径
12 // 一般发起请求的时候,浏览器都会在请求头中加入一个 origin 字段,表示当前请求的来源
13 //    例如我有一个页面:http://127.0.0.1:3000/index.html
14 //    页面中发起了一个请求:/api/users 浏览器会帮你自动加上 http://127.0.0.1:3000/api/users 发起请求
15 //    同时在请求头中加入一个源:http://127.0.0.1:3000
16 //    
17 //    这个源到底有什么用?
18 //       有些服务器会根据这个请求的来源来限制一些非法请求
19 //    例如:我在 http://127.0.0.1:3000/index.html 发起了一个 
20 //        http://127.0.0.1:5000/users 的请求
21 //        则该请求的 origin 来源是 http://127.0.0.1:3000
22 //        所以这里的 changeOrigin 表示将请求的来源 origin 改为 http://127.0.0.1:5000
23 //        这样就通过欺骗服务器的方式解决对方对 origin 来源的限制
24 //        欺骗对方服务器我不是代理
25 //        
26 //     pathRewrite 表示路径重写
27 //     举个例子:
28 //       如果我当前请求的是 /api/heros
29 //            则默认代理转发到 http://127.0.0.1:5000/api/heros
30 //       关键是我的服务器的接口没有 /api 前缀
31 //       所以这里我通过 pathRewrite 的方式重写路径的方式修改掉 /api
32 //        那这个时候如果请求 /api/heros
33 //        则先将 /api 重写成 ''
34 //        然后将重写的结果和剩余部分拼接起来发起请求:http://127.0.0.1:5000/heros
35 var jsonPlaceholderProxy = proxy('/api', {
36   target: 'http://127.0.0.1:5000',
37   changeOrigin: true,             // for vhosted sites, changes host header to match to target's host
38   pathRewrite: {
39     '^/api': ''
40   },
41   logLevel: 'debug'
42 })
43 
44 /**
45  * Add the proxy to browser-sync
46  */
47 browserSync.init({
48   server: {
49     baseDir: './',
50     middleware: [jsonPlaceholderProxy]
51   },
52   port: 8080,
53   startPath: '/'
54 })
55 
56 console.log('[DEMO] Server: listening on port 8080')

随后在package.json中配置script字段,npm启动此代理即可,

注意,此处我遇到一个坑,下面参考资料的port:8080写在init函数server选项里面的话,启动出来的端口是一个随机分配的端口

    并不是我们配置的8080口,需要把port选项发到server平级即可启动对应端口

参考资料

https://github.com/chimurai/http-proxy-middleware/blob/master/examples/browser-sync/index.js

猜你喜欢

转载自www.cnblogs.com/herewego/p/9284701.html