Skip to content

Instantly share code, notes, and snippets.

@shafiimam
Last active October 19, 2021 05:15
Show Gist options
  • Save shafiimam/f9dd6fd01442c43f1e4ebf7203400e90 to your computer and use it in GitHub Desktop.
Save shafiimam/f9dd6fd01442c43f1e4ebf7203400e90 to your computer and use it in GitHub Desktop.
Create public api and routing and use CORS

Allow CORS

  1. 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 public API

  1. Create a folder named routes in your server folder
  2. Create js file for your router. ex: productRoutes.js
  3. 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;
  1. Import ProductRoutes in server.js
import productRoutes from './routes/productRoutes';
  1. Koa router uses two function for inported routes from another directory routes() and allowmethods() 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.
  2. Use the imported routes in the server.js file
server.use(productRoutes.routes());
server.use(productRoutes.allowedMethods());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment