重新启动节点服务器后,NodeJS TypeError

时间:2019-05-09 18:39:35

标签: javascript node.js express npm ejs

我正在使用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

有关

1 个答案:

答案 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()行。经过测试,可以正常工作。

相关问题