javascript Express Node.js 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23638026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Express Node.js doesn't work
提问by Abhishek Mhatre
I installed express 4 along with node.js,npm and express-generator on my ubuntu 12.04 and created an app using the following commands:
我在 ubuntu 12.04 上安装了 express 4 以及 node.js、npm 和 express-generator,并使用以下命令创建了一个应用程序:
express test --hogan -c less
cd test && npm install
node app.js
Now what I should get is "Express server running on port 3000" but instead the command simply executes and doesn't leave any message or error. So I have no idea of which port express is running on or whether or not it is running at all. So does anyone know what's going wrong in it? Thanks in advance.
现在我应该得到的是“在端口 3000 上运行的 Express 服务器”,但命令只是执行并且不会留下任何消息或错误。所以我不知道哪个端口 express 正在运行,或者它是否正在运行。那么有谁知道它出了什么问题?提前致谢。
回答by Akshat Jiwan Sharma
The new express generator does not add app.listen
statement in the auto generated app.js file. It could be a bug? What you can do is add a statement like
新的 express 生成器不会app.listen
在自动生成的 app.js 文件中添加语句。这可能是一个错误?你可以做的是添加一个像
app.listen(3000, function () {
console.log("express has started on port 3000");
});
This will instruct express to listen on port 3000 and print out a helpful message on the console as well.
这将指示 express 侦听端口 3000 并在控制台上打印出有用的消息。
回答by Daniel
Auto generated express apps are not supposed to be started by running node app.js
.
不应通过运行node app.js
.
If you look in your package.json
file, you should see something like
如果你查看你的package.json
文件,你应该看到类似的东西
"scripts": {
"start": "node ./bin/www"
}
This is how the auto-generated app is designed to be started. You can start it either by running exactly what it says there (i.e. node ./bin/www"
from the root directory of your project), or the more proper way is to start it using npm start
from the root directory.
这就是自动生成的应用程序的启动方式。您可以通过运行它所说的内容(即node ./bin/www"
从项目的根目录)来启动它,或者更合适的方法是npm start
从根目录启动它。
回答by Juan Marco
I was having this problem locally. I found the line:
我在本地遇到了这个问题。我找到了这一行:
var port = process.env.PORT || 3000;
or
或者
var port =
process.env.PORT ?
process.env.PORT : 3000;
Did not work for me.
没有对我来说有效。
Just gives me "ERR_CONNECTION_REFUSED". But no errors reported from nodemon.
只是给我“ERR_CONNECTION_REFUSED”。但是没有从 nodemon 报告错误。
Solution:Be a bit more robust with the logic:
解决方案:逻辑更健壮一点:
var DEFAULT_PORT = 3000;
var port = DEFAULT_PORT;
var maybe_port = process.env.PORT;
if( typeof maybe_port === "number" ){
port = maybe_port;
}
Then, don't forget:
然后,不要忘记:
app.listen( port );