Node 使用express-http-proxy 做api网关的实现
拷贝代码备忘,filter过滤请求,proxyReqOptDecorator重写请求头,代码如下:
varexpress=require('express'); varproxy=require('express-http-proxy') varapp=express(); app.all('*',function(req,res,next){ res.header("Access-Control-Allow-Origin",req.headers.origin); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("Access-Control-Allow-Credentials","true"); res.header("Content-Type","application/json;charset=utf-8"); if(req.method=='OPTIONS'){ res.header('Access-Control-Allow-Headers',req.headers['access-control-request-headers']); res.send(200);/*让options请求快速返回*/ } else{ next(); } }); //代码转发 app.use('/ProxySSO',proxy(req=>{ returnreq.headers.apiurl },{ filter:function(req,res){ //用户名\系统标识\用户权限 let{systemName,masterName,powers}=req.tokenDecode; const{originalUrl}=req; consturl=originalUrl.replace('/ProxySSO','').split('?')[0]; /** *接口权限检查 *@param{String}url接口地址 *@param{Object}powersrbac权限列表 *@returns{boolean}是否有权限 */ constcheckPowers=(url,powers)=>{ //dosomething } consthasPowers=checkPowers(url,powers); //权限判断 returnhasPowers; }, proxyReqOptDecorator:function(proxyReqOpts,srcReq){ //header增加masterName具体按照自己的需求来 //proxyReqOpts.headers['masterName']=srcReq.tokenDecode.masterName; returnproxyReqOpts; } })); module.exports=app;
到此这篇关于Node使用express-http-proxy做api网关的实现的文章就介绍到这了,更多相关Nodeapi网关内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!