我有一个用 ESModule Typescript 编写的 Node.js 项目,使用 Express.js 和 Inversify。我希望将 Nunjucks 集成为模板引擎,尽管每当我尝试使用 njk 访问端点渲染输出时都会出现以下错误:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (node:_http_outgoing:659:11)
at ServerResponse.header (/home/bailando/projects/learning-platform/node_modules/express/lib/response.js:794:10)
at ServerResponse.contentType (/home/bailando/projects/learning-platform/node_modules/express/lib/response.js:624:15)
at ServerResponse.send (/home/bailando/projects/learning-platform/node_modules/express/lib/response.js:149:14)
at done (/home/bailando/projects/learning-platform/node_modules/express/lib/response.js:1045:10)
at /home/bailando/projects/learning-platform/node_modules/nunjucks/src/environment.js:28:5
at RawTask.call (/home/bailando/projects/learning-platform/node_modules/asap/asap.js:40:19)
at flush (/home/bailando/projects/learning-platform/node_modules/asap/raw.js:50:29)
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
code: 'ERR_HTTP_HEADERS_SENT'
}
这是我的index.ts:
import 'dotenv/config';
import 'reflect-metadata';
import container from './ioc.config.js';
import nunjucks from 'nunjucks';
import { InversifyExpressServer } from 'inversify-express-utils';
const server = new InversifyExpressServer(container);
server.setConfig((app) => {
nunjucks.configure('views', {
autoescape: true,
express: app
});
app.set('view engine', 'njk');
});
const app = server.build();
app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});
我的家.controller.ts:
import { Request, Response } from 'express';
import { controller, httpGet } from 'inversify-express-utils';
@controller('/')
export class HomeController {
constructor() {}
@httpGet('/')
public async getUsers(_: Request, res: Response) {
res.render('home');
}
}
我的
home.njk
现在只是纯文本Hello world
有什么可能出现问题的提示吗?当我重新配置设置以使用 Pug 时,一切都运行良好,所以我想知道 Express 和 Nunjucks 之间是否存在兼容性问题,尽管我几乎确定我过去曾成功地使用过类似的设置。类似地,当我在端点中返回纯字符串时,一切正常。
我已经设法找到解决方法。当我将家庭控制器方法更改为:
时,它会正确呈现@controller('/')
export class HomeController {
@httpGet('/')
public async showHome(@request() req: Request, @response() res: Response) {
return new Promise((resolve, reject) => {
res.render('home', (err, html) => {
if (!err) resolve(html);
reject(err);
});
});
}
}
尽管如此,我仍然很好奇是否可以在没有这个样板的情况下做到这一点。