我对MERN和React有点陌生,到目前为止,服务器端口一直在工作,直到我尝试连接到Mongodb。
require('dotenv').config()
const express = require("express")
const mongoose = require('mongoose')
const workoutRoutes = require('./routes/workouts')
const app = express()
//middleware
app.use(express.json())
app.use((req, res, next) => {
console.log(req.path, req.method)
next()
})
//routes
app.use('/api/workouts', workoutRoutes)
//connect to db
mongoose.connect(process.env.MONGO_URI)
.then(() => {
// listen to port
app.listen(process.env.PORT, () => {
console.log('listening for requests on port', process.env.PORT)
})
})
.catch((err) => {
console.log(err)
})
//listening for requests
app.listen(process.env.PORT, () => {
console.log("listening on port", process.env.PORT)
})
我得到这个错误
Error: listen EADDRINUSE: address already in use :::4000
at Server.setupListenHandle [as _listen2] (node:net:1733:16)
at listenInCluster (node:net:1781:12)
at Server.listen (node:net:1869:7)
at Function.listen (C:\Users\urbai\OneDrive\Desktop\MERN STACK\backend\node_modules\express\lib\application.js:635:24)
at C:\Users\urbai\OneDrive\Desktop\MERN STACK\backend\server.js:25:9
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1760:8)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'EADDRINUSE',
errno: -4091,
syscall: 'listen',
address: '::',
port: 4000
}
Node.js v18.13.0
[nodemon] app crashed - waiting for file changes before starting...
我多次尝试更改端口,关闭任务管理器中的打开节点任务,但仍然存在相同的问题
1条答案
按热度按时间li9yvcax1#
在您的代码中,您尝试启动服务器(侦听)两次。将最后一行更改为:
不要
app.listen()
两次。或者至少不要在同一个端口上做两次。