Tim
Tim

Reputation: 103

How to pass JSON to FetchAPI Response

I'm trying to create Response object and can't figure out how to pass json body in it.

Should I create a ReadableStream? If so, how can I do it?

I'm trying it offhand:

const stream = new ReadableStream({
  start(controller) {
    controller.enqueue(JSON.stringify({message: 'Test'}));
  },
});

new Response(stream, {
  status: 304,
  statusText: 'Not Modified',
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
});

But it doesn't seem to work.

Upvotes: 0

Views: 56

Answers (1)

Tim
Tim

Reputation: 103

Seems I was a little hasty to create a question here. It turned out to be a lot easier than I thought, no ReadableStream required:

new Response(JSON.stringify({message: 'Test'}), {
  status: 418,
  statusText: 'Teapot',
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
});

My mistake was that I tried to set a body to a Response with null body status.

Upvotes: 2

Related Questions