For Workers & Pages, what is the name of the domain?
workers dev
What is the error message?
SyntaxError: Unexpected end of JSON input
What is the issue or error you’re encountering
Error when calling .json() on fetch POST request
What steps have you taken to resolve the issue?
This is probably my own silly mistake (I’m new to Workers), but any help would be appreciated. I’m trying to get the body of a POST request, but I keep seeing an error in the console (“SyntaxError: Unexpected end of JSON input”). Weirdly, there are no other issues. The response returns as expected. I’m not sure what I’m doing wrong.
What are the steps to reproduce the issue?
Create new worker via web
Click “Start with Hello World!”
Input this code:
export default {
async fetch(request, env, ctx) {
var t = await request.json();
return new Response(“Hello world”);//
},
};
Run a POST request with the following body (I’m using the HTTP tab on web to the right of the code):
{“name”:“John Doe”}
Observe error in console when sending request. Error only shows if code has been changed since previous request. The response is normal though.
This error is being generated by the preview tab and the dev enviroment. Each time you change the code and re-deploy then issue a new request to the worker this error is generated as the preview page is requesting your worker with an HTTP GET.
This error is also generated when you set the request type to POST and start typing your json as it makes a request on each change.
Here is some more complete code that will check and prevent these errors in dev tools:
export default {
async fetch(request) {
if (request.method !== "POST") { // Check that the request is POST
return new Response("Please send a POST request with a non-empty JSON body.", { status: 405 });
}
try {
const body = await request.text();
if (!body.trim()) { // Check if the POST body is not empty
return new Response("Error: JSON body is empty", { status: 400 });
}
const data = JSON.parse(body);
return new Response(`Received JSON: ${JSON.stringify(data)}`, {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (err) {
return new Response(`Error parsing JSON: ${err.message}`, { status: 400 });
}
},
};