- Install koa2-cors npm package
npm install koa2-cors
2.In the server.js file Import koa2-cors
import cors from 'koa2-cors'
Use the cors middleware
server.use(cors())
- Create a folder named routes in your server folder
- Create js file for your router. ex: productRoutes.js
- In productRoute.js
import Router from 'koa-router';
const router = new Router();
router.get('/api/products'), async (ctx) => {
try {
ctx.body = {
"status": "success",
"data": "Hello this is from the public API"
}
}
catch(error) {
console.error(error);
}
}
export default router;
- Import ProductRoutes in server.js
import productRoutes from './routes/productRoutes';
- Koa router uses two function for inported routes from another directory
routes()
andallowmethods()
routes()
Returns router middleware which dispatches a route matching the request.allowMethods()
Returns separate middleware for responding to OPTIONS requests with an Allow header containing the allowed methods, as well as responding with 405 Method Not Allowed and 501 Not Implemented as appropriate. - Use the imported routes in the server.js file
server.use(productRoutes.routes());
server.use(productRoutes.allowedMethods());