关于前端:使用-httpproxy-代理-HTTP-请求时遇到的-the-requested-url-is-invalid-错误消息

2次阅读

共计 1735 个字符,预计需要花费 5 分钟才能阅读完成。

应用如下代码创立 HTTP 代理服务器:

const http = require('http');
const httpProxy = require('http-proxy');

const targetUrl = 'https://www.sap.cn/index.html';

const proxy = httpProxy.createProxyServer({
    target: targetUrl,
    secure:false
});

http.createServer(function (req, res) {proxy.web(req, res);
}).listen(8089);

console.log('Proxy listens in 8089');

浏览器输出 http://localhost:8089/,遇到如下谬误音讯:

The requested URL “http://%5bNo%20Host%5d/index.html/”, is invalid.

在 proxy 服务器结构时,增加一行 changeOrigin:true, 后,谬误隐没:

这行代码的作用:

changeOrigin: true/false, Default: false – changes the origin of the host header to the target URL

意思是:置为 true,能够将 host header 的 origin 值,更改为指标 URL。

咱们能够把 HTTP server 结构时指定的 target 字段,设置到 proxy.web 办法里,依然工作:

第 15 行 web 办法的第三个参数,接管一个字段为 target 的 JSON 对象,值为冀望跳转到的指标 url.

同第一种办法不同,大家留神到,这种办法,咱们在地址栏里输出了 localhost:8089, 关上被代理的百度网页后,地址栏里的 localhost:8089 放弃不变:

const http = require('http');
const httpProxy = require('http-proxy');

const targetUrl = 'https://www.sap.cn/index.html';

const baidu = 'https://www.baidu.com';

const proxy = httpProxy.createProxyServer({
    //target: targetUrl,
    changeOrigin:true,
    secure:false
});

http.createServer(function (req, res) {
    proxy.web(req, res, {target: baidu});
}).listen(8089);

console.log('Proxy listens in 8089');

然而对于 sap 官网来说,有一个重定向的行为:

Access to fetch at ‘https://wappass.baidu.com/sta…’ (redirected from ‘http://localhost:8085/baidu’) from origin ‘http://localhost:8085’ has been blocked by CORS policy: The ‘Access-Control-Allow-Origin’ header has a value ‘http://wappass.baidu.com’ that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

失常状况下,应用 fetch 申请绝对路径:

在 Chrome 开发者工具 network 标签页里,没有察看到 OPTIONS 申请:

间接就是 HTTP GET CORS 谬误了。当站点 A 尝试从站点 B 获取内容时,站点 B 能够发送一个 Access-Control-Allow-Origin 响应标头,通知浏览器该页面的内容能够从某些起源拜访。源是一个域 (domain),加上一个计划(scheme) 和端口号。

正文完
 0