Closed sendking closed 2 years ago
It is probably because cors middleware isn't awaiting next()
.
// BAD: This will lead to UnhandledPromiseRejection
router
.use(async (req, res, next) => {
next();
})
.use(async (req, res, next) => {
next();
})
.use(async () => {
throw new Error("💥");
});
// GOOD
router
.use(async (req, res, next) => {
await next(); // next() is awaited, so errors are caught properly
})
.use((req, res, next) => {
return next(); // this works as well since we forward the rejected promise
})
.use(async () => {
throw new Error("💥");
// return new Promise.reject("💥");
});
@nakashkumar
// This way is useful, but i think is not the best.
router.use(async (req, res, next) => {
await cors()
await next()
})
// This way will be broken, but maybe better.
router.use(cors())
face this issue too , v0.12.2 is works fine.
function apiHandler(req, res) {
// here there are some error throw from handler , the next process will be exit.
// handler is `async`
return handler(req, res, getConfig(config), ops, opts);
};
use(...).post(async (req, res) => {
return apiHandler(req, res)
// if error throw from. apiHandler(), the whole process will be exit.
});
To use express middleware in v1, you must wrap it with expressWrapper
(on latest next
version)
import { createRouter, expressWrapper } from "next-connect";
import cors from "cors";
const router = createRouter();
router.use(expressWrapper(cors());
See https://github.com/hoangvvo/next-connect#expressjs-compatibility
It works fine in https://www.npmjs.com/package/next-connect/v/1.0.0-next.3. Thx! 😊
https://github.com/sendking/next-connect/pull/1/files
Some problems when i use cors middleware first...