EADDRINUSE:添加require时地址已在使用中



根据请求,我的服务器应该执行cmd命令和deploy.js文件。一切都很好,但如果我添加这行const { getSimpleMessage } = require('../src/server'),我会得到端口3000已经在使用的错误。为什么会发生这种情况?

Server.js:

app.post("/", (req,res) =>{ 
console.log("Get from /"); 
SimpleMessage = 'Hello world';
exec('npx hardhat run scripts/deploy.js --network goerli',
(error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log("v error")
console.log(`exec error: ${error}`);
}
});
res.send("Server received the request");
});
// starting the server
app.listen(3000, () => {
console.log('listening on port 3000');
});

Deploy.js:

const { getSimpleMessage } = require('../src/server');           //THIS LINE CAUSES ERROR
async function main() {
const HelloWorld = await ethers.getContractFactory("HelloWorld");
// Start deployment, returning a promise that resolves to a contract object
const hello_world = await HelloWorld.deploy("HelloWorld");   
console.log("Contract deployed to address:", hello_world.address);
}

main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});

我使用命令运行该文件:node-src/server。

deploy.js文件中运行require('../src/server');时,会运行src/server.js部件的所有代码,包括部件app.listen(3000, ...)。如果服务器已经在运行(使用node src/server.js命令(,则端口3000已经在使用,并且运行deploy.js(从而尝试运行app.listen(3000, ...)(会导致错误。

最简单的解决方案是将逻辑分离。如果要在src/server.js文件中保留getSimpleMessageapp声明,则可以从文件中删除app.listen部分,转而导出app对象。然后创建例如index.js文件,该文件导入app对象并运行app.listen部分。

./index.js:

const { app } = require('./src/server');
// starting the server
app.listen(3000, () => {
console.log('listening on port 3000');
});

然而,我建议更干净的解决方案是将getSimpleMessage函数放在一个单独的文件中(如果可能的话(。

当服务器正在运行并收到POST /请求时,它会部署Deploy.js,这会导致

app.listen(3000, ...)

server.js中的命令在另一个过程中再次执行。然后将有两个进程都在侦听端口3000,这将导致观察到的错误。

也许您需要将getSimpleMessage函数从server.js文件中分离出来。

最新更新