英文:
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 () => {
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());
})();
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论