i5ting / koa-generator

Koa' application generator for 1.x and 2.x( Express-style and support all middlewares include async/await )
https://github.com/17koa/koa-generator
MIT License
972 stars 110 forks source link

use `koa2 -e` ,and visit `http://127.0.0.1:3000`,response : "Not Found" #6

Closed xiongwilee closed 8 years ago

xiongwilee commented 8 years ago

I use $ koa2 -eto generate a project,

and change default HTML engine to ejs , then start server with npm start,

and visit: http://127.0.0.1:3000 , it response "Not Found".

I debug like this:

co module:

function onFulfilled(res) {
  var ret;
  try {
    console.log(res,'!!!!!!!!!!!'); // and 
    ret = gen.next(res);
  } catch (e) {
    return reject(e);
  }
  next(ret);
}

koa@next module:

function respond(ctx) {
  console.log(ctx.body, 'respond');
  // allow bypassing koa
  if (false === ctx.respond) return;
      ...

and start server with DEBUG=* npm start, and find the log shows like :

undefined '!!!!!!!!!!!!!!!!!!!!!!!'
undefined 'respond'    # respond executed before template parser
  --> GET / 404 27ms -
<!DOCTYPE html>
<html>
  <head>
    <title>Hello World Koa!</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>Hello World Koa!</h1>
    <p>Welcome to Hello World Koa!</p>
  </body>
</html>
 !!!!!!!!!!!!!!!!!!!!!!!

koa default function(respond) executed before HTML parser , why? and how to debug it then?

xiongwilee commented 8 years ago

妈蛋 , 作者是中国人, 用中文重新描述下问题, 求大神解答:

我用koa2 -e生成了一个koa2的ejs项目,然后把默认模板引擎改成了ejs

然后用npm start启动server,然后访问 http://127.0.0.1:3000 , 结果浏览器返回:Not Found, (访问http://127.0.0.1:3000/users 正常)

感觉是模板引擎除了问题,然后我在co和koa源码分别加了两个console:

    // co 源码
function onFulfilled(res) {
  var ret;
  try {
    console.log(res,'!!!!!!!!!!!'); // debug
    ret = gen.next(res);
  } catch (e) {
    return reject(e);
  }
  next(ret);
}

    // koa源码
function respond(ctx) {
  console.log(ctx.body, 'respond'); // debug
  // allow bypassing koa
  if (false === ctx.respond) return;
      ...

然后用DEBUG=* npm start启动后,访问发现日志的是这样的:

undefined '!!!!!!!!!!!!!!!!!!!!!!!'
undefined 'respond'   # respond先执行了,然后才获取到模板引擎编译之后的HTML片段
  --> GET / 404 27ms -  
<!DOCTYPE html>
<html>
  <head>
    <title>Hello World Koa!</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>Hello World Koa!</h1>
    <p>Welcome to Hello World Koa!</p>
  </body>
</html>
 !!!!!!!!!!!!!!!!!!!!!!!

koa的内置方法——respond怎么会在模板解析之前执行呢?太奇怪了,然后再怎么调试呢,求调试方法?

xiongwilee commented 8 years ago

大概找到原因了,在 consolidate.js 里的read方法,有一个异步读取模板文件的fs.readFile方法,改成同步方法就好了:fs.readFileSync

但是,最根本的原因是什么?

i5ting commented 8 years ago

@xiongwilee 哈哈,新版已经解决了,如果有问题,请反馈(前一段比较忙,不好意思)

xiongwilee commented 8 years ago

赞!