首页 > 解决方案 > http-proxy 错误:必须提供正确的 URL 作为目标

问题描述

这是我第一次尝试 http-proxy。我收到错误消息:

Error: Must provide a proper URL as target

代码:

httpProxy = require('http-proxy');

httpProxy.createServer(function(req, res) {
  proxy.web(req, res, { target: 'http://127.0.0.1:10002' });
}).listen(3001);

我从 curl 知道我的网站在端口 10002 上运行。

正确的 URL 是什么样的?还是这个错误实际上意味着完全不同的东西?开箱即用无法访问端口 10002,我正在通过 Internet 进行测试。

标签: node.jshttp-proxy

解决方案


您需要使用http模块创建服务器,而不是http-server.

替换httpProxy.createServerrequire('http').createServer

const httpProxy = require('http-proxy')
const proxy = httpProxy.createProxyServer({}) // I added this line to make this full snippet working

require('http').createServer(function (req, res) {
  proxy.web(req, res, { target: 'http://127.0.0.1:10002' })
}).listen(3001)

推荐阅读