I dont know why but if function not get error, it work perfectly , but when it get error, catch always display
res.end is not a function
it like i can't use res in catch, but in try res still work, Am i missing something?
import axios from "axios";
import { NextApiResponse } from "next";
const handler = async (res: NextApiResponse): Promise<void> => {
return new Promise((resolve, _) => {
axios({
method: "get",
headers: { "Content-type": "application/json" },
url:
process.env.NODE_ENV === "production"
? "https://.../refresh_token"
: "http://localhost:4000/refresh_token",
withCredentials: true,
})
.then((response) => {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.setHeader("Cache-Control", "max-age=180000");
res.end(JSON.stringify(response.data));
resolve();
})
.catch((error) => {
res.statusCode = 500;
res.end(JSON.stringify((error as Error).message));
resolve();
});
});
};
export default handler;
CodePudding user response:
The first parameter in your handler
function should be a NextApiRequest
object, not a NextApiResponse
object:
const handler = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => { //...
Since req
is expected to be the first parameter, passing res
there will mean calling end
on the NextApiRequest
object — an error because end
doesn't exist there.