相关疑难解决方法(0)

如何使用其他URL复制Request对象?

我正在编写一个包装器fetch,我想在发出请求之前向URL添加内容,例如识别查询参数.我无法弄清楚如何Request使用与原始URL不同的URL 制作给定对象的副本.我的代码看起来像:

// My function which tries to modify the URL of the request
function addLangParameter(request) {
    const newUrl = request.url + "?lang=" + lang;
    return new Request(newUrl, /* not sure what to put here */);
}

// My fetch wrapper
function myFetch(input, init) {
    // Normalize the input into a Request object
    return Promise.resolve(new Request(input, init))
        // Call my modifier function
        .then(addLangParameter)
        // Make the actual request
        .then(request => fetch(request));
}
Run Code Online (Sandbox Code Playgroud)

我尝试将原始请求作为第二个arguent放到Request构造函数中,如下所示:

function …
Run Code Online (Sandbox Code Playgroud)

javascript fetch-api

11
推荐指数
1
解决办法
1548
查看次数

在 ES6 中修改新请求对象的 URL

我只是在玩FetchAPI,我遇到了一些我似乎无法找到答案的东西。如果我像这样创建一个新的请求对象:

let request = new Request('http://www.foo.com', {
  method: 'GET',
  mode: 'no-cors',
  headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
  })
});
Run Code Online (Sandbox Code Playgroud)

如果我然后尝试修改 URL(向其附加查询字符串),我会在浏览器中收到错误 ( Cannot assign to read only property)。我知道通常对于一个对象,您可以将其设置writable为“True”,但是这对于请求对象是否相同?

我问的原因是我试图将查询字符串附加到 URL 的末尾。这些options在另一个对象中,我已经得到了它的值并连接成一个字符串,所以它是这样的:

number=1&id=130&foo=bar 等等。

我是否试图过度设计我在这里所做的事情?

javascript request ecmascript-6 fetch-api

7
推荐指数
2
解决办法
2904
查看次数

标签 统计

fetch-api ×2

javascript ×2

ecmascript-6 ×1

request ×1