当前位置: 首页 > Web前端 > HTML5

使用 http-proxy 代理 HTTP 请求时遇到的 the requested url is invalid 错误消息

时间:2023-04-05 19:35:49 HTML5

使用http-proxy代理HTTP请求时遇到Therequestedurlisinvalid错误信息;consttargetUrl='https://www.sap.cn/index.html';constproxy=httpProxy.createProxyServer({target:targetUrl,secure:false});http.createServer(function(req,res){proxy.web(req,res);}).listen(8089);console.log('代理监听8089');浏览器输入http://localhost:8089/,遇到如下错误信息:请求的URL“http://%5bNo%20Host%5d/index.html/”无效。在构建代理服务器时,添加一行changeOrigin:true,错误消失:这行代码的作用:c??hangeOrigin:true/false,Default:false-改变hostheader的来源为目标URL意思是:设置为true,您可以将主机标头的原始值更改为目标URL。我们可以将构造HTTP服务器时指定的target字段设置到proxy.web方法中,它仍然会起作用:第15行web方法的第三个参数接收一个字段为target的JSON对象,值为预期跳转到目标url与第一种方法不同。大家注意到,在这个方法中,我们在地址栏中输入了localhost:8089。打开代理的百度网页后,地址栏localhost:8089不变:consthttp=require('http');consthttpProxy=require('http-proxy');consttargetUrl='https://www.sap.cn/index.html';constbaidu='https://www.baidu.com';constproxy=httpProxy.createProxyServer({//target:targetUrl,changeOrigin:true,secure:false});http.createServer(function(req,res){proxy.web(req,res,{target:baidu});}).listen(8089);console.log('代理监听8089');但是对于sap官网,有一个重定向行为:Accesstofetchat'https://wappass.baidu.com/sta...'(redirectedfrom'http://localhost:8085/baidu')fromorigin'http://localhost:8085'已被CORS策略阻止:'Access-Control-Allow-Origin'标头的值'http://wappass.baidu.com'不等于提供的来源。让服务器发送标头r具有有效值,或者,如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用CORS的资源。一般情况下,使用fetch请求绝对路径:在Chrome开发者工具网标签页中,观察不到OPTIONS请求:直接HTTPGETCORS报错。当站点A尝试从站点B获取内容时,站点B可以发送一个Access-Control-Allow-Origin响应标头来告诉浏览器页面的来源。可以从某些来源访问内容。源是一个域,加上一个方案和端口号。