简体   繁体   中英

Express router and routes Node.js

I get this error when I try to route my

My code

'use strict';

const express = require('express');
const app = express ();
const chatCat = require ('./app');


app.set('port', process.env.PORT || 3000);
app.use(express.static('public'));
app.set('view engine', 'ejs');

app.use('/', chatCat.router);



app.listen(app.get('port'), () => {
    console.log('running on port:', app.get('port'));
});

Error

throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
          ^

I tried routing but it keeps giving me errors from my express.js.

Try this code:

var express = require('express');
var app = express();


 app.set('port', process.env.PORT || 3000);
 app.use(express.static('public'));
 app.set('view engine', 'ejs');

var chatCat = require('./app');
app.use('/',chatCat);

app.listen(port,function(){
    console.log("Server is running on port: "+port);
});

Try creating app with this https://expressjs.com/en/starter/generator.html it will create nice structure for your project. As for your error - it needs to be express middleware function . You can't import router from your app.js as it don`t have such property. If you want to have route described here use:

    app.method('/yourRoute', function(req, res, next){
       //your middleware code
    });

also change this:

   app.listen(app.get('port'), () => {
     console.log('running on port:', app.get('port'));
   });

to this:

 app.listen(3000);

And you can change 3000 to any unused port you want

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