2

I'm using NextJS API Routes and am building for a tutorial. In both production and development, I want the JSON to be formatted. The original code that does not format the JSON and does include the header I want "application/json" is the following:

export default async function handler(req, res) {
   ..
   const speakers = [{id: 1, name: 'sp1'},{id: 2, name: 'sp2'}];
   res.status(200).json(speakers);

I do want to format the JSON and I have tried the following and it does format the JSON but I can't figure out how to attach the content type header "application/json" to the response.

   res.status(200).send(JSON.stringify(speakers,null,2));

*** Though I tagged this question with express, I think there is a NextJS specific component to it.

Peter Kellner
  • 14,748
  • 25
  • 102
  • 188
  • Does this answer your question? [node and express send json formatted](https://stackoverflow.com/questions/32679505/node-and-express-send-json-formatted) – eol Mar 26 '21 at 13:44
  • Unfortunately not. I did see that question and tried several of the variations suggested including `res.type('json').send(JSON.stringify(speakers, null, 2));`. All those result in "API resolved without sending a response for /api/speakers, this may result in stalled requests.". I think that NextJS might not be using express exactly but that's in a level of NextJS I don't really understand. That is, this is not a pure express question. – Peter Kellner Mar 26 '21 at 14:08
  • 3
    I just found another example and this worked: ` res.setHeader('Content-Type', 'application/json');` – Peter Kellner Mar 26 '21 at 14:18
  • 2
    Doesn't `res.status(200).json(JSON.stringify(speakers,null,2));` do the trick? – juliomalves Mar 26 '21 at 18:07
  • @juliomalves, did not try that. – Peter Kellner Mar 26 '21 at 22:13

0 Answers0