api route in express for nextjs code example
Example 1: node express dynamic route and error handler
app.use(function (req, res, next) {
res.status(404).send("Sorry can't find that!")
})
Example 2: example route in koa and controller
exports.resultsController = async(ctx, next) => {
ctx.body = "Hello Wordl from get";
await next();
}
exports.createController = async (ctx, next) => {
ctx.body = JSON.stringify(ctx.request.body);
await next();
}
=================================
const {resultsController, createController} = require("../controllers/user.controller");
const Router = require("koa-router");
const router = new Router();
router.get("/", resultsController);
router.post("/", createController);
module.exports = router.routes();
=================================
const koa = require("koa");
const app = new koa();
const server = require("http").createServer(app.callback());
const bodyParser = require("koa-body");
const logger = require("koa-logger");
const userRoute = require("./routes/user.route");
app.use(bodyParser());
app.use(logger());
app.use(userRoute);
server.listen(3000, () => console.log("server is running"));