node http-proxy模块的使用及报错处理

nodejs中,有时候我们会碰到一些需要转发请求的情况,这时候使用代理就比较方便了,下面介绍下 http-proxy 的使用

一.express中简单使用的代码

const httpProxy = require('http-proxy');
const proxyInstance = httpProxy.createProxyServer({}); // 创建代理实例
function proxy(req, res, next) {
    proxyInstance.web(req, res, { target: 'http://127.0.0.1:6064', changeOrigin: true }); // 代理的目标地址, changeOrigin改变源重要 否则转发之后路径信息是不会改变的,会报错误1 
    // const url = `${'http://127.0.0.1:6064'}${req.originalUrl}`;
    // req.pipe(request(url)).pipe(res);
}

二.在使用中我遇到两个问题:

    1.Error: connect ECONNREFUSED and app starts listening (详细见:https://github.com/nodejitsu/node-http-proxy/issues/1268)

       解决办法: 尝试添加 changeOrigin: true 参数

    2.request aborted

       解决办法:  请求转发的时候如果使用express框架 切记 注释 // app.use(express.json()); 这一行

   

感谢您的阅读!如果文章中有任何错误,或者您有更好的理解和建议,欢迎和我联系!

发布了29 篇原创文章 · 获赞 18 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Baby_lucy/article/details/92811091