node作为中间层 —> 跨域请求java后台接口(使用http-proxy-middleware中间件)
情景:利用node的express 作为中间层,跨域调取java后台接口,由于java接口对session有判断,因此每次请求都必须在req的headers中需要带上cookie,否则接口报500错误,通过多次尝试,终于成功调取到接口,代码如下:
1 const express = require('express'); 2 const path = require('path'); 3 const proxyMiddleware = require('http-proxy-middleware'); 4 5 6 // default port where dev server listens for incoming traffic 7 const port = 3335; 8 9 const app = express(); 10 11 //设置cookie 12 let cookie; 13 function relayRequestHeaders(proxyReq, req) { 14 if (cookie) { 15 proxyReq.setHeader('cookie', cookie); 16 } 17 }; 18 19 function relayResponseHeaders(proxyRes, req, res) { 20 let proxyCookie = proxyRes.headers["set-cookie"]; 21 if (proxyCookie) { 22 cookie = proxyCookie; 23 } 24 }; 25 26 27 let options = { 28 target: 'http://192.168.1.2:8081', // target host 29 changeOrigin: true, // needed for virtual hosted sites 30 pathRewrite: { 31 '^/': '/Edit-WS/', // rewrite path 32 }, 33 onProxyReq: relayRequestHeaders, 34 onProxyRes: relayResponseHeaders, 35 }; 36 37 // 静态资源 处理 38 app.use(express.static(path.join(__dirname + '/WebRoot'))); 39 40 // 访问登录页(/) 41 app.get('/', function(req, res, next) { 42 console.log('test============='); 43 let options = { 44 root: __dirname + '/WebRoot/', 45 dotfiles: 'deny', 46 headers: { 47 'x-timestamp': Date.now(), 48 'x-sent': true 49 } 50 }; 51 52 let fileName = 'index_2x.html'; 53 res.sendFile(fileName, options, function(err) { 54 if (err) { 55 console.log(err); 56 res.status(err.status).end(); 57 } else { 58 console.log('Sent:', fileName); 59 } 60 }); 61 }); 62 63 // 匹配的路由(正则) 64 app.use('/**/*.do', proxyMiddleware(options)); 65 66 const server = app.listen(port);