我正在使用Node.js,Express框架和EJS模板构建一个Web应用。
这是我的服务器:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.set('view engine', 'ejs');
app.get('/', (req,res) => {
res.render('home', {
headline : 'We are always on a mission for Clearn Benglauru'
});
});
app.use(express.static(__dirname, '/public'));
app.listen(PORT, () => {
console.log(`The app is running on port : ${PORT}`);
});
启动服务器后,出现此错误:
TypeError: Object prototype may only be an Object or null: /public
at Function.create (<anonymous>)
at Function.serveStatic [as static] (<DIRECTORY>\node_modules\serve-static\index.js:48:21)
at Object.<anonymous> (<DIRECTORY>\test:12:23)
可能与Node.JS object prototype may only be an Object or null with Redis
有关答案 0 :(得分:1)
使用模块path
来服务您的公用文件夹。
const express = require('express');
const app = express();
const path = require('path');
const PORT = process.env.PORT || 3000;
app.set('view engine', 'ejs');
app.get('/', (req,res) => {
res.status(200).send('Ok!');
});
app.use(express.static(path.join(__dirname, 'public')));
app.listen(PORT, () => {
console.log(`The app is running on port : ${PORT}`);
});
我没有EJS或EJS视图文件,因此在示例中,我用res.render
替换了res.status().send()
行。经过测试,可以正常工作。