user3322664
user3322664

Reputation:

Router is not defined in KOA2

I have two files, one of them is the app.js and the otherone is api.js. In the first file I have :

  app.use(setHeader)
  app.use(api.routes())
  app.use(api.allowedMethods())

And in api.js I have:

import KoaRouter from 'koa-router';
const api = new Router();

//Validatekey
const validateKey = async (ctx, next) => {
const { authorization } = ctx.request.headers;
console.log(authorization);
if (authorization !== ctx.state.authorizationHeader) {
  return ctx.throw(401);
}
   await next();
}

api.get('/pets', validateKey, pets.list);

When I run the project a error message is throw: Router is not defined.

But If I write both files together, the application go fine.

Anybody knows the problem?

I have solved with var Router = require('koa-router')

Upvotes: 2

Views: 382

Answers (2)

BHUVNESH KUMAR
BHUVNESH KUMAR

Reputation: 401

The import is currently not implemented in nodejs, neither is it supported in the latest ES2015(ES6). You will need to use a transpiler like Babel to use import in code.I advice that avoid transpiler as it cause performance issues on production just go with require and it will work.

Upvotes: 2

gevorg
gevorg

Reputation: 5055

Obviously Nodejs does not support import / export syntax and using require will solve your problem.

However it is possible to make import work on Node.js by using babel transformers.

Look the following answer for more information https://stackoverflow.com/a/37601577/972240

Upvotes: 0

Related Questions