将Express函数传递给另一个调用HTTPS createServer的文件



根据 Node 最佳实践,建议将 HTTP 和 Express 服务器 API 分开。

我的问题是createServer期望一个函数作为第二个参数,但我正在传入一个对象。

应用.js

const config = require('./config');
const express = require('express');
const app = express();
app.use(express.static(__dirname + config.STATIC_DIR));
app.use(express.json());
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
// POST /agent used for registration requests
app.post('/agent', (req, res) => {
console.log('Received registration request from ', req.body);
return res.send('Received a POST HTTP method');
});

服务器.js

const fs = require('fs');
const config = require('./config');
const mysql = require('mysql2/promise');
const app = require('./app');
const sslConfig = {
key: fs.readFileSync(config.SSL_KEY),
cert: fs.readFileSync(config.SSL_CERT)
};
const server = require('https').createServer(sslConfig, app);
const io = require('socket.io')(server);

我收到以下错误:

throw new errors.ERR_INVALID_ARG_TYPE('listener', 'Function', listener);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type Function. Received type object
at checkListener (events.js:55:11)
at _addListener (events.js:214:3)
at Server.addListener (events.js:272:10)
at new Server (https.js:67:10)
at Object.createServer (https.js:85:10)
at Object.<anonymous> (/Users/Code/server.js:18:8)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)

如果要将 SSL 配置传递到createServer方法中,需要进行哪些更改?

我能够通过在app.js末尾添加以下行来解决此问题:

module.exports = app;

相关内容

  • 没有找到相关文章

最新更新