我尝试在AdonisJS控制器中使用node-http-proxy,但是得到了错误信息
The "url" argument must be of type string. Received type function导致错误的行是proxy.web(request, response, { target: urlToProxy });
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 });
}发布于 2019-07-02 14:54:17
最后,我稍微接近了一点,但还没有完全修复。最接近的部分是意识到http-proxy是通过缓冲区传递数据的,所以我必须这样做
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令牌通过代理之前对其进行验证。
发布于 2019-08-23 21:44:42
您是如此接近,我想做一些类似的事情,并将代理封装在promise中,以便我们可以等待代理返回,然后再响应我们的响应:
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;我想我会给你一个完整的答案,任何人遇到这个问题。
https://stackoverflow.com/questions/56834200
复制相似问题