The above is the directory structure, and the routing is as follows:
const router = require('koa-router')();
const views = require('koa-views');
router.use(views(__dirname + '/views'));
router.get('/', async (ctx, next) => {
await ctx.render('index');
});
module.exports = router;
When running the above, the following error will be reported:
So I changed the sentence about the path to
router.use(views(__dirname + '../views'));
The error message becomes
It’s very helpless. It can run after changing it to this:
router.use(views(__dirname + '/../views'));
It is normal now, but this is obviously unreasonable. How should I change it?
Post the code of index.js conveniently:
const Koa = require('koa');
const router = require('./routes/routes');
const app = new Koa();
// log request URL:
app.use(async (ctx, next) => {
console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
await next();
});
// add router middleware:
app.use(router.routes());
app.listen(3000);
console.log('app started at port 3000...');
Thanks!
淡淡烟草味2017-06-28 09:27:34
Your routes.js
file is in the /Users/dark/Works/drip-file/routes
folder, so the value of __dirname
is /Users/dark/Works/drip-file/routes
, __dirname + '/views'
is equal to /Users/dark/Works/drip-file/routes/views
, so when accessing the index file, it will search under this folder, so it was not found.
When you change it to __dirname+'/../views'
, you will search in the folder /Users/dark/Works/drip-file/views
, so you can find it.
If you want to change it to __dirname+'/views'
, if there is no need to create a separate routes
folder, just put the routes.js file into the same folder as the index.js file.