首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在AdonisJS控制器中使用node-http-proxy

如何在AdonisJS控制器中使用node-http-proxy
EN

Stack Overflow用户
提问于 2019-07-01 18:38:14
回答 2查看 162关注 0票数 0

我尝试在AdonisJS控制器中使用node-http-proxy,但是得到了错误信息

代码语言:javascript
复制
The "url" argument must be of type string. Received type function

导致错误的行是proxy.web(request, response, { target: urlToProxy });

代码语言:javascript
复制
async proxy({ request, response }){
    var resource = await Resource.query().where('uri', request.url()).with('service.user').with('userSecurity').first()
    resource = resource.toJSON()
    if(!resource.service.active){
      return response.status(404).send(`Parent service '${resource.service.title}' is disabled`)
    }
    if(!resource.active){
      return response.status(404).send(`Resource is disabled`)
    }
    if(resource.userSecurity.length <= 0) {
      return response.status(403).send(`You are not permitted to access that resource. Contact ${resource.service.user.first_name} ${resource.service.user.last_name} (${resource.service.user.email})`)
    }

    var urlToProxy = url.resolve(resource.service.basepath, request.originalUrl())
    var proxy = httpProxy.createProxyServer()

    proxy.web(request, response, { target: urlToProxy });

  }
EN

回答 2

Stack Overflow用户

发布于 2019-07-02 14:54:17

最后,我稍微接近了一点,但还没有完全修复。最接近的部分是意识到http-proxy是通过缓冲区传递数据的,所以我必须这样做

代码语言:javascript
复制
proxy.web(req, res, { target: data.service.basepath})
    proxy.on('error', function(err, req, res){
      console.log("There was an error", err)
    })

    proxy.on('proxyRes', async (proxyRes, request, response) =>{
      var body = new Buffer('')
      proxyRes.on('data', (data)=>{
        body = Buffer.concat([body, data])
      })

      proxyRes.on('end', ()=>{
        body = body.toString()
        try{
          res.send(body)
        }catch(err){
        }
      })
    }); 

然而,我仍然不能让它工作,因为控制器在http-proxy完成请求之前返回。

最后,我编写了一个独立的代理应用程序,并使用主应用程序在JWT令牌通过代理之前对其进行验证。

票数 0
EN

Stack Overflow用户

发布于 2019-08-23 21:44:42

您是如此接近,我想做一些类似的事情,并将代理封装在promise中,以便我们可以等待代理返回,然后再响应我们的响应:

代码语言:javascript
复制
const proxy = httpProxy.createProxyServer();
const prom = new Promise((resolve, reject) => {
    proxy.web(request.request, response.response, {
        target: urlToTarget
    }, (e) => {
        reject(e);
    });

    proxy.on('proxyRes', function (proxyRes, req, res) {
        let body = [];
        proxyRes.on('data', function (chunk) {
            body.push(chunk);
        });
        proxyRes.on('end', function () {
            body = Buffer.concat(body).toString();
            resolve(body);
        });
    });
});

const result = await prom;
response.body(result);
return response;

我想我会给你一个完整的答案,任何人遇到这个问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56834200

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档