Node 代理访问的实现

2020-06-17 05:35:07易采站长站整理

NODE代理访问

1. 场景

本地开发,代理访问,防止跨域(一般通过webpack配置代理即可),特殊情况如携带一些自定义的登录cookie则需要通过自己写node
作为一种server中间层,单线程异步可以缓解服务器压力。长链接websocket通常使用node搭建

2. 技术框架

node – koa2 体量小,轻便易用。
路由koa-router koa配套路由,中间件支持async
koa2-request 基于async对 request的封装,这里本人git上找的,可靠性带考量,若基于生产环境建议使用request自行封装
koa-bodyparser 请求参数解析格式化-中间件

3. 上代码

3.1 创建应用 app.js


const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
// 路由
const router = require('./router')
const app = new Koa()

app.use(
bodyParser({
// 返回的对象是一个键值对,当extended为false的时候,键值对中的值就为'String'或'Array'形式,为true的时候,则可为任何数据类型。
extended: true
})
)

3.2 允许跨域 app.js


app.use(async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', '*')
ctx.set('Access-Control-Allow-Headers', 'content-type')
ctx.set(
'Access-Control-Allow-Methods',
'OPTIONS,GET,HEAD,PUT,POST,DELETE,PATCH'
)
await next()
})

3.2 使用路由


// app.js

app.use(router.routes())

// router.js

const Router = require('koa-router')
let koaRequest = require('./httpRequest')
const router = new Router()

router.get('/*', async (ctx, next) => {
const url = setQuestUrl(ctx.url)
try {
let res = await koaRequest(url, 'GET', ctx)
ctx.body = res
} catch (err) {
ctx.body = err
}
})

router.post('/*', async (ctx, next) => {
const url = setQuestUrl(ctx.url)
try {
let res = await koaRequest(url, 'POST', ctx)
ctx.body = res
} catch (err) {
ctx.body = err
}
})

function setQuestUrl(url) {
if (/^/t/.test(url)) {
return 'host1'+ url.replace(/^/t/, '')
}
if (/^/xt/.test(url)) {
return 'host2' + url.replace(/^/xt/, '')
}
}

module.exports = router

router.get(‘/*’, async (ctx, next) => {}) koa路由 ‘/*’ 为通配符,匹配所有get请求;next方法调用表示进入下一个中间件;
ctx请求上下文,ctx.request.body post请求参数
koa的中间件原理 洋葱圈模型: