简体   繁体   中英

Node Js TypeError with morgan: app.use is not a function

I am new to node js and following a tutorial on scotch.io . I've imported morgan for logging requests, but when I run the code I get TypeError: app.use is not a function . This is my code for 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;

And for 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"
  }
}

require('express') returns a function, which you should call in order to get the express application. Therefore:

const app = express;

should be changed to:

const app = express();

Try this, change app=express; to app=express(); 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM