【问题标题】:How to modify the url of a request object in fetch API?如何在 fetch API 中修改请求对象的 url?
【发布时间】:2020-05-31 15:34:46
【问题描述】:

我正在使用由 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;
    });
}

【问题讨论】:

    标签: javascript http fetch httprequest httpresponse


    【解决方案1】:

    你可以这样做:

    async function handleRequest(request) {
    
      #change the value of request.url and then...
    
      return fetch({...request, url: "someUrl"})
        .then(response => {
            return response;
        });
    }
    

    这将用“someUrl”覆盖网址 希望这会有所帮助:)

    【讨论】:

    • 这不起作用,因为Request 的大多数属性都是不可枚举的,因此它们不会包含在传播中。试试看:const request = new Request({method: 'POST', url: '/'}); const requestData = {...request}; console.log(requestData.method) - 它将打印 undefined 而不是 'POST'
    猜你喜欢
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    相关资源
    最近更新 更多