![](/img/trans.png)
[英]Node EADDRINUSE: address already in use :::3000 when testing with jest and supertest
[英]EADDRINUSE: address already in use when adding require
根據請求,我的服務器應該執行一個 cmd 命令和 deploy.js 文件。 一切正常,但是如果我添加此行const { getSimpleMessage } = require('../src/server')
我會收到端口 3000 已在使用中的錯誤。 為什么會這樣?
服務器.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');
});
部署.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。
當服務器運行並收到一個POST /
請求時,它會部署Deploy.js
,這會導致
app.listen(3000, ...)
server.js
中的命令在另一個進程中再次執行。 然后會有兩個進程都在監聽端口 3000,這會導致觀察到的錯誤。
也許您需要將getSimpleMessage
函數從server.js
文件中分離出來。
當你運行require('../src/server');
在deploy.js
文件中,運行src/server.js
部分的所有代碼,包括部分app.listen(3000, ...)
。 如果服務器已經在運行(使用node src/server.js
命令),則端口 3000 已經在使用中並且正在運行deploy.js
(因此嘗試運行app.listen(3000, ...)
)會導致錯誤。
最簡單的解決方案是分離邏輯。 如果您想在src/server.js
文件中同時保留getSimpleMessage
和app
聲明,您可以從文件中刪除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
函數放在一個單獨的文件中(如果可能的話)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.