【问题标题】:cannnot find render() on Koa context在 Koa 上下文中找不到 render()
【发布时间】:2018-09-25 09:14:50
【问题描述】:

我是 koa@2 的新手,我正在尝试重定向到特定页面。我能够重定向到静态页面,但我想向该页面发送一些数据以显示。我搜索了执行此操作的方法,发现 ctx(Koa Context) 有一个方法 render(),它需要两个 args(1st-page url, 2nd - locals(our data))。

我试过了:

const Koa = require('koa');
const render = require('koa-ejs');
const path = require('path');

const app = new Koa();
render(app, {
  root: path.join(__dirname, 'view'),
  layout: 'template',
  viewExt: 'html',
  cache: false,
  debug: true
});

app.use(async function (ctx) {
  await ctx.render('user');
});

app.listen(7001);

还有这个:

import co from 'co';
import render from 'koa-ejs';

render(app, options);
app.context.render = co.wrap(app.context.render);

app.use(async (ctx, next) => {
    await ctx.render(view, locals);
});

来自:herehere

但我总是得到属性渲染在 ctx 上不存在。 我尝试将 ctx 的类型从 BaseContex 更改为 IRouter,但发布的内容保持不变。 我觉得我需要将render属性附加到ctx,但我不知道该怎么做。

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: node.js typescript redirect koa koa2


    【解决方案1】:

    您可以尝试使用第一种方式:

    ctx.render 的第二个参数是你的数据

    index.js

    const Koa = require('koa');
    const render = require('koa-ejs');
    const path = require('path');
    
    const app = new Koa();
    render(app, {
      root: path.join(__dirname, 'view'),
      layout: 'template',
      viewExt: 'html',
      cache: false,
      debug: true
    });
    
    app.use(async function (ctx) {
      await ctx.render('user', { a: 'apple', b: 'ball', c: 'cat' });
    });
    
    app.listen(7001);
    

    在同一级别上,您需要有一个 view 文件夹,其中包含 template.html,因为您将布局指定为模板并将 viewExt 指定为 html

    这是 template.html 的示例:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Template</title>
        <link rel="stylesheet" href="">
    </head>
    <body>
        <h1>THIS IS THE TEMPLATE!!!</h1>
        <h2><%= a %></h2>
        <h2><%= b %></h2>
        <h2><%= c %></h2>
    </body>
    </html>
    

    另外,我认为最好发布 package.json 文件

    {
      "name": "stovrflow",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "dependencies": {
        "koa": "^2.5.1",
        "koa-ejs": "^4.1.1"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-20
      • 2015-08-15
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      相关资源
      最近更新 更多