繁体   English   中英

如何修改请求正文

[英]How to modify request body

我正在向员工发送发帖请求。 帖子正文内容。

{
    "name": "value",
    "name2": "value2"
}

如果name2 = value2,那么我要修改它:

{
    "name": "value",
    "name2": "NewValue"
}

我正在使用此脚本。

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});
async function handleRequest(r) {
  return new Response(r.body, {
    headers: {
      "Content-Type": "application/json",
      corsHeaders
    }
  })
}

如果我json.parse(r.body)不起作用。 我怎样才能做到这一点? 我听说r.body是ReadableStream,所以如何进行修改。 请帮忙。 谢谢。

来自MDN文档

request.json().then(function(data) {
  // do something with your data
});

这应该可以帮助您入门:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  let requestJSON = await request.json()

  // your logic here

  return await fetch(request, {body: JSON.stringify(requestJSON)})
}

您可能希望将JSON解析限制为满足以下条件的请求:

(request.method ===“ POST” && request.headers.get(“ Content-Type”)===“ application / json”)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM