类型错误:字符串不是一个函数?
大家好,我是 Node js 的新手
我正在尝试运行以下代码
var express = require('express'),
app = express(),
cons = require('consolidate'); // Templating library adapter for Express
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.get('/', function(req, res){
res.render('hello', { name : 'World' });
});
app.get('*', function(req, res){
res.send('Page Not Found', 404);
});
app.listen(8080);
console.log('Express server started on port 8080');
然后出现错误
TypeError: string is not a function at EventEmitter.render (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\application.js:569:12) at ServerResponse.render (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\response.js:961:7) at C:\Users\YAm\Desktop\mongodb\work\test_coso.js:10:6 at Layer.handle [as handle_request] (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\router\route.js:131:13) at Route.dispatch (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\router\layer.js:95:5) at C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\router\index.js:277:22 at Function.process_params (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\router\index.js:330:12) at next (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\router\index.js:271:10) at expressInit (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\middleware\init.js:33:5) at Layer.handle [as handle_request] (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\router\index.js:312:13) at C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\router\index.js:280:7 at Function.process_params (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\router\index.js:330:12) at next (C:\Users\YAm\Desktop\mongodb\work\node_modules\express\lib\router\index.js:271:10)
只需查看 express res.render() 的文档。我认为您的语法有问题。
// send the rendered view to the client
res.render('index');
// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function(err, html) {
res.send(html);
});
// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function(err, html) {
// ...
});
代码没有任何问题,对我来说运行良好
执行以下操作来调试问题
-
检查
views
文件夹中的hello.html
文件,删除所有 html 代码,然后尝试放入一些简单的“Hello Word” - 创建一个新文件夹并复制粘贴 js 脚本和 views 文件夹,然后尝试 npm install express、consolidate 和 swig
- 检查节点版本 v5.5.0,它运行良好,没有任何 问题