【问题标题】:Node Js TypeError with morgan: app.use is not a function摩根的Node Js TypeError:app.use不是一个函数
【发布时间】:2019-03-12 17:32:58
【问题描述】:

我是 node js 的新手,并遵循 scotch.io 上的教程。我已经导入 morgan 来记录请求,但是当我运行代码时,我得到 TypeError: app.use is not a function。这是我的 app.js 代码;

const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');

const app = express;

app.use(logger('dev'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.get('*', (req, res) => res.status(200).send({
    message: 'Welcome to deep thinking.'
}));

module.exports = app;

对于 package.json:

{
  "name": "postgres-express-react-node-tutorial",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start:dev": "nodemon ./bin/www",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.3",
    "morgan": "^1.9.1"
  },
  "devDependencies": {
    "nodemon": "^1.18.4"
  }
}

【问题讨论】:

    标签: javascript node.js express typeerror morgan


    【解决方案1】:

    require('express') 返回一个函数,您应该调用该函数以获取 express 应用程序。因此:

    const app = express;
    

    应该改为:

    const app = express();
    

    【讨论】:

    • 哇,谢谢!这行得通。我已经为此苦苦挣扎了一段时间。
    【解决方案2】:

    试试这个,换app=express; to app=express();

    const express = require('express');
    const logger = require('morgan');
    const bodyParser = require('body-parser');
    
    const app = express(); // changed this line
    
    app.use(logger('dev'));
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    
    app.get('*', (req, res) => res.status(200).send({
        message: 'Welcome to deep thinking.'
    }));
    
    module.exports = app;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 2018-07-03
      相关资源
      最近更新 更多