如何修改fetch API中请求对象的url?

dov*_*538 5 javascript http httpresponse httprequest fetch

我正在使用由 HTTP 请求触发的 Cloudflare Worker。我想接受传入请求,更改 url 但保持所有其他属性不变,然后发出请求。结构如下:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {

  #change the value of request.url and then...

  return fetch(request)
    .then(response => {
        return response;
    });
}
Run Code Online (Sandbox Code Playgroud)

rud*_*ker 5

要克隆 Request 对象,但更改 URL,您可以执行以下操作:

new Request("https://example.com/the/new/url", originalRequest);
Run Code Online (Sandbox Code Playgroud)

在浏览器控制台中尝试一下:

let originalRequest = new Request("https://example.com")
let newRequest = new Request("https://voxviva.app", originalRequest);
Run Code Online (Sandbox Code Playgroud)

检查newRequest。您将不会在任何地方看到旧的 URL。


the*_*a93 -2

你可以这样做:

async function handleRequest(request) {

  #change the value of request.url and then...

  return fetch({...request, url: "someUrl"})
    .then(response => {
        return response;
    });
}
Run Code Online (Sandbox Code Playgroud)

这将用“someUrl”覆盖 url 希望这有帮助:)