2

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')

nole
  • 1,422
  • 4
  • 20
  • 32
  • It was solved, I have change import koaRouter from 'koa-router' by var Router = require('koa-router') – nole Nov 23 '16 at 16:41
  • If you are interested you can make `import` work too by using `babel` transformers. – gevorg Nov 24 '16 at 02:49

2 Answers2

2

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.

BHUVNESH KUMAR
  • 391
  • 4
  • 15
0

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

Community
  • 1
  • 1
gevorg
  • 4,835
  • 4
  • 35
  • 52