cloudflare-workers - 将重定向传递给访问者?
问题描述
当我的工作人员遇到来自源的重定向时,它会跟随它并返回内容,而不是将重定向传递给访问者。有谁知道如何强制工作人员使用从源接收到的相同重定向进行响应?
这与代理一起使用。
http://server.one/proxy-path/old-directory/
请求被发送到http://server.two/old-directory/
它以 301 响应 /new-directory/。最终结果应该是访问者被发送到,http://server.one/proxy-path/new-directory/
但发生的是工作人员遵循重定向并从/proxy-path/old-directory/
路径下的 /new-directory/ 提供内容。
希望这是有道理的。感谢您的任何见解!
解决方案
以下重定向是fetch()
. 您可以像这样覆盖它:
fetch(url, {redirect: "manual"})
但是您的脚本可能存在更深层次的问题。通常,传入的event.request
已经redirect = "manual"
设置了属性,所以如果你event.request
直接传递给fetch()
,那么你会得到你想要的行为。如果您看到重定向被自动跟踪,这表明您没有传递原始请求对象,此外,您已经删除了一些原始请求的属性。
当人们编写如下代码时,通常会发生这种情况:
// INCORRECT: Loses request properties and headers!
let newUrl = rewriteUrl(event.request.url);
event.respondWith(fetch(newUrl));
有时人们意识到这会丢失标题,因此他们尝试将它们添加回来,例如:
// STILL INCORRECT: Loses request properties other than headers!
let newUrl = rewriteUrl(event.request.url);
event.respondWith(fetch(newUrl, {headers: event.request.headers}));
正确的做法是将整个request
对象作为第二个参数传递给fetch()
,例如:
// CORRECT
let newUrl = rewriteUrl(event.request.url);
event.respondWith(fetch(newUrl, event.request));
这样,所有请求的属性,包括redirect
、method
、body
等,都会被复制过来。
请注意,如果要修改 URL和标头,则需要执行两个步骤:
let newUrl = rewriteUrl(event.request.url);
let newHeaders = rewriteHeaders(event.request.headers);
// Create a new Request object with the new headers.
let newRequest = new Request(event.request, {headers: newHeaders});
// Fetch the new URL using the new Request object.
event.respondWith(fetch(newUrl, newRequest));
或者,您可以利用您自己创建的 Request 对象(与您在事件中收到的对象相反)是可变的这一事实:
let newUrl = rewriteUrl(event.request.url);
// Create a new Request object with modified URL.
let newRequest = new Request(newUrl, event.request);
// Modify the headers directly on this object.
newRequest.headers.set("X-Foo", "Bar");
// Forward it on.
event.respondWith(fetch(newRequest));
推荐阅读
- c - 运行分配静态内存的简单程序时出现 DEADLYSIGNAL 错误
- c# - 注入 ILogger
- android - 预填充的 Android Room 数据库保持为空
- flutter - 为什么 ElevatedButton 被拉伸以适应屏幕的宽度?
- javascript - 按下输入文本字段时增加 div 元素的 paddingTop,否则减少
- ios - 在 react-native run-ios 上构建失败
- python - 虚拟环境如何在 python 中工作(内部)
- android - Jetpack Compose 中的垂直嵌套滚动
- php - 通过字符串路径获取数组的值
- python - 如何在使用 load_img 加载图像之前裁剪图像?