【问题标题】:NodeJS TypeError after restarting the node server [closed]重新启动节点服务器后的NodeJS TypeError [关闭]
【发布时间】:2019-05-09 18:39:35
【问题描述】:

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

【问题讨论】:

  • 我预计我会得到反对票。伙计们,请给出解决方案,而不是为无意的错误投票。我真的需要你的帮助。
  • 什么问题,多解释一下..我们猜不出你的问题..
  • 如果我提供我的存储库链接可以吗?请帮帮我。
  • app.use(express.static(__dirname, '/public'));这是给我带来麻烦的线路。当我们提供没有路径的静态文件时,我们必须连接它。我们不应该使用','。

标签: javascript node.js express npm ejs


【解决方案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() 作为示例。经过测试并且可以工作。

【讨论】:

  • app.use(express.static(__dirname, '/public'));这是给我带来麻烦的线路。当我们提供没有路径的静态文件时,我们必须连接它。我们不应该使用','。
猜你喜欢
  • 2013-11-15
  • 1970-01-01
  • 2015-09-18
  • 2011-04-21
  • 2012-07-06
  • 2018-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多