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

发布时间:2019-06-03 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了koa 利用 node-fetch 写个自己的代理脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

在公司的项目中用了 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的结果。

脚本宝典总结

以上是脚本宝典为你收集整理的koa 利用 node-fetch 写个自己的代理全部内容,希望文章能够帮你解决koa 利用 node-fetch 写个自己的代理所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: