如何将React默认端口3000更改为其他端口?
默认情况下,ReactJS 应用程序在端口 3000 上运行。Express.js 应用程序也在同一端口 3000 上运行。如果您要同时运行这两个应用程序,则会发生冲突。您需要更改其中之一的端口。
在 ReactJS 中,更改端口号的最简单方法是通过终端将名为 PORT 的环境变量设置为所需的端口号。例如,这里我们将端口号更改为5000。
如果你在Linux和Mac终端中使用,那就是
$export PORT=5000
或者如果您在 Windows 中使用,命令略有不同
$env:PORT=5000
最后启动npm
npm start
注意:它适用于 .env 文件
如果你想修改你的package.json
默认为
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
并修改为
"start": "PORT=2000 react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
最后再次运行
我用这个
修改你的 package.json Linux 和 MacOS :
"start": "PORT=3006 react-scripts start"
or
"start": "export PORT=6000 react-scripts start"
或Windows
"start": "set PORT=6000 && react-scripts start"
最后重启npm
我尝试使用它来更改默认端口并成功,所以你可以尝试
如果有更好的解决方案请帮助我