nextjs api handler issues error about not sending a response when response sent. wai?

for this code:
export default function handler(req: NextApiRequest, res: NextApiResponse) {
// return promptController.specific(req, res);
fs.readFile('json/foo.json', 'utf-8', (err, data) => {
if (err) {
console.error('booo', err);
return;
}
console.log('yay!>>', data);
res.status(200).send(data);
});
}
export default function handler(req: NextApiRequest, res: NextApiResponse) {
// return promptController.specific(req, res);
fs.readFile('json/foo.json', 'utf-8', (err, data) => {
if (err) {
console.error('booo', err);
return;
}
console.log('yay!>>', data);
res.status(200).send(data);
});
}
I'm getting this error API resolved without sending a response for /api/foo, this may result in stalled requests.. can anyone help with why this is happening? I heard that the sending needs to happen at the top level and not within a callback. this makes no sense to me why, since this sounds like it's being suggested that a promise is returned from the handler and the docs don't mention anything about promises needing to be returned.
4 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
alan
alan2y ago
thanks. I refactored it to something like that but I guess I'm curious as to why the original version isn't working
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
alan
alan2y ago
thanks. that's a good point. I used the following for imports:
import type { NextApiResponse } from "next";
import path from "path";
import fs from "fs";
import type { NextApiResponse } from "next";
import path from "path";
import fs from "fs";
Want results from more Discord servers?
Add your server