Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask question.(5)

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

ITtutoria

ITtutoria Logo ITtutoria Logo

ITtutoria Navigation

  • Python
  • Java
  • Reactjs
  • JavaScript
  • R
  • PySpark
  • MYSQL
  • Pandas
  • QA
  • C++
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Python
  • Science
  • Java
  • JavaScript
  • Reactjs
  • Nodejs
  • Tools
  • QA
Home/ Questions/How can I handle - app.use() requires a middleware function?
Next
Answered
Evan Garcia
  • 14
Evan Garcia
Asked: May 18, 20222022-05-18T18:31:06+00:00 2022-05-18T18:31:06+00:00In: javascript

How can I handle – app.use() requires a middleware function?

  • 14

. Advertisement .

..3..

. Advertisement .

..4..

Here is the program I run:

var express= require('express');
 var bodyParser= require('body-parser');
 var morgan = require('morgan');
 var config=require('./config');
 var app= express();
 var mongoose=require('mongoose');
 //var User=require('./database/user')
 mongoose.connect('mongodb://localhost:27017/db',function(err){
  if(err){
  console.log(err);
  }
  else{
  console.log("connected!");
  }
 });
 
 app.use(bodyParser.urlencoded({extended: true })); //if false then parse only strings
 app.use(bodyParser.json());
 app.use(morgan('dev'));//log all the requests to the console
 var api=require('./app/routes/api')(app,express);
 app.use('/api',api);
 app.get('*',function(req,res){
  res.sendFile(__dirname + '/public/views/index.html');
 }); // * means any route
 
 app.listen(config.port,function(err){
  if(err){enter code here
  console.log(err);
  }
  else{
  console.log("The server is running");
  }
 });
 module.exports = router;
var User = require('../models/user');
 var Event = require('../models/event');
 var config = require('../../config');
 var secret = config.secretKey;
 
 module.exports = function (app, express) {
  var api = express.Router();
  app.use()
 
  api.post('/signup', function (req, res) {
  var user = new User({
  name: req.body.name,
  username: req.body.username,
  password: req.body.password
  });
  user.save(function (err) {
  if (err) {
  res.send(err);
  return;
  }
  res.json({
  message: 'User created!'
  });
  });
 
  });
 
  api.get('/users', function (req, res) {
  User.find({}, function (err, users) {
  if (err) {
  res.send(err);
  return;
  }
  res.json(users);
  });
  });
 
  api.post('/eventfeed', function (req, res) {
  var event = new Event({
  name: req.body.name,
  location: req.body.location,
  description: req.body.description,
  price: req.body.price,
  rating: req.body.rating
  });
 
  event.save(function (err) {
  if (err) {
  res.send(err);
  return;
  }
  res.json({
  message: 'Event created!'
  });
  });
  });
 
  // utility function for sorting an array by a key in alpha order
  api.get('/sortby_price', function (err) {
  if (err) return err;
  // utility function for sorting an array by a key in parsed numeric order
  else {
  function sortArrayNum(arr, key) {
  arr.sort(function (a, b) {
  return parseInt(a[key], 10) - parseInt(b[key], 10);
  });
  }
 
  var dicts = EventSchema.saved;
  for (var i = 0; i < dicts.length; i++) {
  var terms = dicts[i].terms;
  sortArrayNum(terms, "price");
  }
  }
  return api;
  });
 }

After I run, it returns an error:

TypeError: app.use() requires middleware functions
  at EventEmitter.use (c:\Users\MY APY\WebstormProjects\Main\node_modules\express\lib\application.js:209:11)
  at module.exports (c:\Users\MY LAPY\WebstormProjects\Main\app\routes\api.js:10:9)
  at Object. (c:\Users\MY LAPY\WebstormProjects\Main\server.js:20:36)
  at Module._compile (module.js:460:26)
  at Object.Module._extensions..js (module.js:478:10)
  at Module.load (module.js:355:32)
  at Function.Module._load (module.js:310:12)
  at Function.Module.runMain (module.js:501:10)
  at startup (node.js:129:16)
  at node.js:814:3

Does anyone have any suggestions for the problem below: app.use() requires a middleware function in the javascript – How to correct it?

requires a middleware function
  • 2 2 Answers
  • 863 Views
  • 0 Followers
  • 0
Answer
Share
  • Facebook
  • Report

2 Answers

  • Voted
  • Oldest
  • Recent
  • Random
  1. Best Answer
    lyytutoria Expert
    2022-06-27T10:29:59+00:00Added an answer on June 27, 2022 at 10:29 am

    The cause:

    You have got this error because in your api.js the line of number 10 is not correct:

    app.use()

    A function with 3 parameters is required for app.use:

    // a middleware which has no mount path; gets performed for each requirement to the app
    app.use(function (req, res, next) {
    console.log('Time:', Date.now());
    next();
    });

    Solution:

    You can do as the following in the case you want to use this middleware by only few chosen paths:

    // a middleware which is put on /user/:id; will be executed for any types of HTTP requirement to /user/:id
    app.use('/user/:id', function (req, res, next) {
    console.log('Request Type:', req.method);
    next();
    });
    
    // a path and the handle function of it (middleware system) which handles GET requirements to /user/:id
    app.get('/user/:id', function (req, res, next) {
    res.send('USER');
    });
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  2. Lina Perez
    2022-05-25T20:46:38+00:00Added an answer on May 25, 2022 at 8:46 pm

    This was the problem I faced when I left.

    module.exports = router;

    In my Routes.js. We need to export all routes.

    In my server.js I had

    var mainRoutes = require('./Routes.js')
    app.use(mainRoutes)

    Check your ‘app/routes/api” file to verify that it is exportable.

    • 7
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question
  • How to Split String by space in C++
  • How To Convert A Pandas DataFrame Column To A List
  • How to Replace Multiple Characters in A String in Python?
  • How To Remove Special Characters From String Python

Explore

  • Home
  • Tutorial

Footer

ITtutoria

ITtutoria

This website is user friendly and will facilitate transferring knowledge. It would be useful for a self-initiated learning process.

@ ITTutoria Co Ltd.

Tutorial

  • Home
  • Python
  • Science
  • Java
  • JavaScript
  • Reactjs
  • Nodejs
  • Tools
  • QA

Legal Stuff

  • About Us
  • Terms of Use
  • Privacy Policy
  • Contact Us

DMCA.com Protection Status

Help

  • Knowledge Base
  • Support

Follow

© 2022 Ittutoria. All Rights Reserved.

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.