修改ES6

时间:2017-03-24 16:30:47

标签: javascript ecmascript-6 request fetch-api

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

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

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

我问的原因是我试图将一个查询字符串附加到URL的末尾。这些options位于另一个对象中,我将其中的值和连接成一个字符串,以便它类似于:

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

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

2 个答案:

答案 0 :(得分:1)

Request对象在设计上是不可变的,请勿尝试对其进行更改。

我希望clone()实例方法接受能够调整克隆对象的选项,但事实并非如此。所以我想出了这个功能:

function appendQuery(urlOrReq, queryString) {
    // make sure we deal with a Request object even if we got a URL string
  const req = urlOrReq instanceof Request ? urlOrReq : new Request(urlOrReq);

  const {
    cache, credentials, headers, integrity, method,
    mode, redirect, referrer, referrerPolicy, url, body
  } = req;

  // Don't add query string if there's none
  const urlWithQuery = url + (!queryString ? '' : '?' + queryString);

  return new Request(urlWithQuery, {
    cache, credentials, headers, integrity, method,
    mode, redirect, referrer, referrerPolicy, body
  })
}

TypeScript中的内容相同(仅第一行不同)

function appendQuery(urlOrReq: RequestInfo, queryString?: string): Request {
    // make sure we deal with a Request object even if we got a URL string
  const req = urlOrReq instanceof Request ? urlOrReq : new Request(urlOrReq);

  const {
    cache, credentials, headers, integrity, method,
    mode, redirect, referrer, referrerPolicy, url, body
  } = req;

  // Don't add query string if there's none
  const urlWithQuery = url + (!queryString ? '' : '?' + queryString);

  return new Request(urlWithQuery, {
    cache, credentials, headers, integrity, method,
    mode, redirect, referrer, referrerPolicy, body
  })
}

这是它的工作方式:

const req = new Request('https://google.com')
appendQuery(req, 'foo=42')
// => Request {method: "GET", url: "https://google.com?foo=42", headers: Headers, destination: "", referrer: "about:client", …}

答案 1 :(得分:0)

您可以使用以下新网址将旧请求中的所有属性复制到新请求中:

const init = { 
  method: 'GET',
  mode: 'no-cors',
  headers: new Headers({
    'Content-Type': 'application/x-www-form-urlencoded'
  })
};
const oldRequest = new Request("https://old-url.com", init);
const newRequest = new Request("https://new-url.com", oldRequest);

console.log(newRequest.mode === oldRequest.mode); // true
console.log(newRequest.headers.get('Content-Type') === oldRequest.headers.get('Content-Type')); // true
console.log(newRequest.method === oldRequest.method); // true