Created
August 16, 2024 11:51
-
-
Save jldec/3ee3a3e0dd6332688572a6a40eb1e46f to your computer and use it in GitHub Desktop.
Example of Response.json() static method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default { | |
async fetch(request) { | |
return Response.json({ | |
date: Date(), | |
headers: Object.fromEntries(request.headers), | |
cf: request.cf | |
}); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Response: json() static method
People commonly call
<response>.json()
instance method to parse a json response body of afetch()
request.But did you know that there is also a
Response.json(data, [options])
static method which returns a newResponse
with your json-stringifieddata
, and adds thecontent-type: application/json
header?For more details, see https://developer.mozilla.org/en-US/docs/Web/API/Response/json_static
Try it out yourself in the Cloudflare workers sandbox
Worker deployed to https://json.jldec.workers.dev/