koa 利用 node-fetch 写个自己的代理

使用Node-fetch搭建koa代理
本文介绍了一种利用Node-fetch库在koa框架中实现HTTP请求代理的方法。通过简单的代码示例,展示了如何代理GET和POST请求,并成功将请求转发到目标服务器。

在公司的项目中用了 koa 向前端(还是我)提供数据接口和渲染页面。有一些操作是和 Java 端交互,所以需要写一些代理转发请求,从网上找了一些koa的代理库,要不就是bug横生;要不就是功能不完全,只能代理 get 请求,于是用 node-fetch 写了个简单的 proxy ,代码挺简单的,写篇博文记录下。

用到了 fetch api,可以看 node-fetch

// proxy.js
import fetch from 'node-fetch'

export default (...args) => {
  return fetch.apply(null, args).then(function (res) {
    return res.text()
  })
}
}

// 没错,就是这么简单,稍微把fetch封装下就可以了


// app.js
import koa from 'koa'
import proxy from './proxy'

const app         = koa()
const proxyServer = koa()

app.use(function* (next) {
  if ('/users' === this.path && 'GET' === this.method)
    this.body = yield proxy('http://localhost:8087/users')
  if ('/user' === this.path)
    this.body = yield proxy('http://localhost:8087/user', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: 'Hubot',
        login: 'hubot',
      })
    })
  yield next
})

proxyServer.use(function* (next) {
  if ('/users' === this.path && 'GET' === this.method)
    this.body = {
      'test': 1
    }
  if ('/user' === this.path && 'POST' === this.method) {
    this.body= {
      'data' : `yes, it's right`
    }
  }
  yield next
})

app.listen(8086)
proxyServer.listen(8087)
console.log('server start 8086')
console.log('server start 8087')

上面 app.js 中创建了两个 server,8086端口为代理 server, 8087端口为被代理的 server,访问 localhost:8086/users 会返回 {"test": 1},说明get请求代理成功,同理访问 localhost:8086/user,会返回
{ "data": "yes, it's right"},说明成功代理了post请求并返回了被代理server的结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值