改变fetch的响应,而不是创建一个新的。

huangapple go评论57阅读模式
英文:

Change response of fetch instead of creating a new one

问题

我需要获取一个文件并将获取到的响应传递给另一个函数但在此过程中我需要更改响应主体我提出的代码如下

    const fetchResponse = await fetch(event.request);

    const text_of_response = await fetchResponse.text();
    text_of_response = text_of_response.replace("MARCADOR1","ON-LINE");
    
    return fetchResponse;

当然上面的代码不会起作用因为我在一个变量中更改了响应文本如何将其放回原始响应中
英文:

I need to fetch a file and forward the response of the fetch to another function but in between I need to change the body. The code I came up is this:

	const fetchResponse = await fetch(event.request);

    const text_of_response = await fetchResponse.text();
	text_of_response = text_of_response .replace("MARCADOR1","ON-LINE");
	
	return fetchResponse;

Of course the code above will not work because I changed the response text in a variable. How do I put it back in the original response?

答案1

得分: 1

以下是翻译好的部分:

(async () => {
  
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
  const text = await response.text();
  
  
  // change your text as you like
  const posts = JSON.parse(text);
  const transformed = posts.map(post => post.body).join(' ');
  
  const transformedResponse = new Response(transformed, {
    status: response.status,
    statusText: response.statusText,
    headers: Object.fromEntries(response.headers.entries())
  });
  
  console.log(await transformedResponse.text());

})();

希望这对您有所帮助。如果您有任何其他需要,请随时告诉我。

英文:

You can make a copy of the response manually:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

(async () =&gt; {
  
  const response = await fetch(&#39;https://jsonplaceholder.typicode.com/posts&#39;);
  const text = await response.text();
  
  
  // change your text as you like
  const posts = JSON.parse(text);
  const transformed = posts.map(post =&gt; post.body).join(&#39; &#39;);
  
  const transformedResponse = new Response(transformed, {
    status: response.status,
    statusText: response.statusText,
    headers: Object.fromEntries(response.headers.entries())
  });
  
  console.log(await transformedResponse.text());

})();

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月8日 01:16:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425673.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定