在Node.js Express上使用中间件设置简单服务器时出错

时间:2018-06-20 04:54:07

标签: javascript node.js express

我对Node Express相当陌生,并且正在尝试使用中间件设置一个简单的服务器来处理路由。 我收到的错误是TypeError: Router.use() requires a middleware function but got a Object 该错误是由于app.get('/', require(routes));行引起的。有人知道我需要在这里作为中间件功能吗?

//server.js
http = require('http');
let port = process.env.PORT || 3000;
let host = '127.0.0.1';
var express = require('express');
var app = express();
var routes = './api/routes/positions';

app.use('/', require(routes));

http.createServer(app).listen(port);
console.log('Listening at http://' + host + ':' + port);

//#########################
//positions.js
const express = require('express');
var router = express.Router();

router.get('/', (err, req, res, next) => {
    res.status(200).json({
    message: "hello from server"
    });
});

module.exports.router;

3 个答案:

答案 0 :(得分:1)

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('ag:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3002');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

答案 1 :(得分:1)

您从positions.js文件中以错误的方式导出了模块。

您需要写

module.exports = router

而不是

module.exports.router

您编写的内容会将一个新的密钥router绑定到exports对象,但是尚未为其分配任何值,因此它将恢复为默认的空对象{}

现在express期望有一个功能,但有对象,因此出错。您可以通过检查require(routes)文件中的server.js来进行验证。

更新(建议)

请研究此格式的代码。

const http = require('http');
const express = require('express');

const routes = require('./api/routes/positions');

const port = process.env.PORT || 3000;
const host = '127.0.0.1';

const app = express();

app.use('/', routes);

http.createServer(app).listen(port);
console.log('Listening at http://' + host + ':' + port);

如果您想阅读更多项目,可以阅读我写的这本boilerplate。它有点旧,但可能会为您服务。

答案 2 :(得分:0)

尝试一下:

     //server.js
        let port = process.env.PORT || 3000;
        let host = '127.0.0.1';
        var express = require('express');
    var app = express();
    var routes = require('./api/routes/positions');

    http.createServer(app).listen(port);
    console.log('Listening at http://' + host + ':' + port);

    //#########################
    //positions.js
    const express = require('express');
    var router = express.Router();
    router.use('/', routes);
   app.use('/', routes);
    router.get('/', (err, req, res, next) => {
        res.status(200).json({
        message: "hello from server"
        });
    });

    module.exports = router;