gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:19:57 25 4
gpt4 key购买 nike

根据Node Best Practices ,建议将 HTTP 和 Express 服务器 API 分开。

我的问题是 createServer 需要一个函数作为第二个参数,但我传入了一个对象。

app.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');
});

server.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;

关于node.js - 将 Express 函数传递给另一个调用 HTTPS createServer 的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58358387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com