一个简单的node.js服务器在本地工作但不在heroku

时间:2014-09-22 12:31:00

标签: node.js git heroku

编写一个简单的服务器,在端口3000上侦听/请求并打印Hello World\n

iamfaiz@HP /f/projects
$ mkdir nodeapp

iamfaiz@HP /f/projects
$ cd nodeapp/

iamfaiz@HP /f/projects/nodeapp
$ touch package.json

iamfaiz@HP /f/projects/nodeapp
$ touch app.js

iamfaiz@HP /f/projects/nodeapp
$ touch Procfile

iamfaiz@HP /f/projects/nodeapp
$ node app.js
Listening at port 3000

app.js

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3000, '127.0.0.1');
console.log('Listening at port 3000');

的package.json

{
  "name": "SimpleNodeApp",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Faiz Ahmed <iamfaizahmed123@gmail.com> (http://google.com/)",
  "license": "ISC"
}

Procfile

web: node app.js

简单目录结构根目录中的所有文件:

Directory structure

初始化并提交到git repository之后:

$ git push heroku master
Initializing repository, done.
Counting objects: 8, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (8/8), 915 bytes | 0 bytes/s, done.
Total 8 (delta 1), reused 0 (delta 0)

-----> Node.js app detected

       PRO TIP: Specify a node version in package.json
       See https://devcenter.heroku.com/articles/nodejs-support

-----> Defaulting to latest stable node: 0.10.32
-----> Downloading and installing node
-----> Exporting config vars to environment
-----> Installing dependencies
       npm WARN package.json SimpleNodeApp@1.0.0 No description
       npm WARN package.json SimpleNodeApp@1.0.0 No repository field.
       npm WARN package.json SimpleNodeApp@1.0.0 No README data
-----> Cleaning up node-gyp and npm artifacts
-----> Building runtime environment
-----> Discovering process types
       Procfile declares types -> web

-----> Compressing... done, 5.4MB
-----> Launching... done, v3
       http://tranquil-reaches-1850.herokuapp.com/ deployed to Heroku

To git@heroku.com:tranquil-reaches-1850.git
 * [new branch]      master -> master

iamfaiz@HP /f/projects/nodeapp (master)
$ heroku open
Opening tranquil-reaches-1850... done

您可以自己查看:https://tranquil-reaches-1850.herokuapp.com/

1 个答案:

答案 0 :(得分:2)

您不得收听127.0.0.1,而应收听0.0.0.0

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3000, '0.0.0.0');

我还建议你让端口监听env变量,如下所示:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(process.env.PORT, '0.0.0.0');