webpackdevserver 报错Something is already running on port 3000 不一定是因为端口被占用
也有可能是你没有开localhost 绑定域名 导致域名解析失败
跟踪代码发现:
如果本地服务报错 会进入
listen(port, 'localhost', err => {
if (err) {
console.log('进入2',err)
return handleError(err)
}
// 4. check current ip
listen(port, address.ip(), (err, realPort) => {
if (err) {
console.log('进入1')
return handleError(err)
}
callback(null, realPort)
})
})
function handleError() {
port++
if (port >= maxPort) {
debug(
'port: %s >= maxPort: %s, give up and use random port',
port,
maxPort
)
port = 0
maxPort = 0
}
tryListen(host, port, maxPort, callback)
}
而没进入一次这个函数 port都会累加一次 进入这个err的原因就是没有绑定host
err信息打印出来是这样的:
Error: getaddrinfo ENOTFOUND localhost at errnoException (dns.js:28:10) at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:73:26) code: 'ENOTFOUND', errno: 'ENOTFOUND', syscall: 'getaddrinfo', hostname: 'localhost'
翻译后大概意思就是没有绑定host 无法进行dns解析
导致在调用对比时候出现问题
devserver调用函数
function choosePort(host, defaultPort) {
return detect(defaultPort, host).then(
port =>
new Promise(resolve => {
// 这里做判断 此时port唯一 是你设置的值 相等直接resolve(port)不相等则会在控制台弹出选择随机port 意味着处于报错状态(可能是由于host 没有配置127.0.0.1)
if (port === defaultPort) {
return resolve(port);
}
const message =
process.platform !== 'win32' && defaultPort < 1024 && !isRoot()
? `Admin permissions are required to run a server on a port below 1024.`
: `Something is already running on port ${defaultPort}.`;
if (isInteractive) {
// clearConsole();
const existingProcess = getProcessForPort(defaultPort);
const question = {
type: 'confirm',
name: 'shouldChangePort',
message:
chalk.yellow(
message +
`${existingProcess ? ` Probably:\n ${existingProcess}` : ''}`
) + '\n\nWould you like to run the app on another port instead?',
default: true,
};
inquirer.prompt(question).then(answer => {
if (answer.shouldChangePort) {
resolve(port);
} else {
resolve(null);
}
});
} else {
console.log(chalk.red(message));
resolve(null);
}
}),
err => {
throw new Error(
chalk.red(`Could not find an open port at ${chalk.bold(host)}.`) +
'\n' +
('Network error message: ' + err.message || err) +
'\n'
);
}
);
}