从零开始,做一个NodeJS博客(一):Heroku上的最简NodeJS服务器

标签:NodeJS,Heroku


0

这里是这个伪系列的第一篇,因为我也不知道自己能不能做完,然后到底能做成什么样子。总之,尽力而为吧,加油。

1 Heroku App 的构成

Heroku 所谓的 NodeJS App ,看起来像一个npm模块,需要一个package.json,语法也跟npm模块的语法几乎一样。
需要在里面写明运行的Node版本及npm版本,以及需要的其他模块依赖及版本。

必须的几个文件:

  • package.json //定义引擎及依赖
  • Procfile //告诉Heroku,App所需要的权限(网络什么的),运行什么命令启动你的App
  • server.js //总得有个JS文件才能跑吧,不过不限制名字

package.json

{
  "name": "blog-node",
  "version": "1.0.0",
  "description": "rocka's node blog",
  "engines": {
    "node": "6.3.1",
    "npm": "3.10.3"
  },
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Rocket1184/NodeServerTest.git"
  },
  "author": "r0cka",
  "license": "MIT"
}

Procfile

web: node server.js

1 开始写服务器

我对这个服务器没什么大要求,只要能返回个404页面就行。相当于一个HelloWorld。
所以我们先需要一个404页面,404.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Error: Not Found</title>
    <style>
        h1,
        p {
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>Error: 404 Not Found</h1>
    <p>File not exist, please check your url.</p>
    <hr>
    <p>Node.js - v6.3.1</p>
</body>
</html>

没啥好说的,一个随随便便的404就好。

然后开始接收请求,准备返回404页面了~~~

这里贴上我的 server.js

'use strict';

var http = require('http');
var fs = require('fs');

var server = http.createServer((request, response) => {
    console.log(request.method + ': ' + request.url);
    if (request.method === 'GET') {
        if (request.url === '/favicon.ico') {
            fs.createReadStream('./favicon.ico').pipe(response);
        } else {
            response.writeHead(200, { 'Content-Type': 'text/html' });
            fs.createReadStream('./404.html').pipe(response);
        }
    }
});

var serverPort = process.env.PORT || 5000;

server.listen(serverPort);

console.log(`[Rocka Node Server] Running at http://127.0.0.1:${serverPort}/`);

用自带的http API创建服务器,处理请求:
如果是GET请求,而且想要拿到 /favicon.ico ,那么用 fs 模块把文件读出来,通过管道传给响应。
否则读取 404.html,把他传出去。

值得注意的一点是,Heroku会为你的App动态分配,端口。如果把服务器监听的端口写死

server.listen(8080);

构建成功,但几乎肯定会出现这个错误:

Web process failed to bind to $PORT within 60 seconds of launch

所以,把端口的值改成Heroku API提供的动态值 process.env.PORT 就好了~~

2 package.json 的一个坑

因为缺乏对npm的了解,我在这一步犯了一个看起来非常小白的错误:
由于我在使用node写服务器时,引用了node自带的fshttp模块,就以为写依赖的时候要把这些也写进去。于是Heroku构建时就各种报错,构建失败:

   npm ERR! Linux 3.13.0-91-generic
   npm ERR! argv "/tmp/build_7f369635973e963166afa93b918df0b4/Rocket1184-NodeServerTest-8575934/.heroku/node/bin/node" "/tmp/build_7f369635973e963166afa93b918df0b4/Rocket1184-NodeServerTest-8575934/.heroku/node/bin/npm" "install" "--unsafe-perm" "--userconfig" "/tmp/build_7f369635973e963166afa93b918df0b4/Rocket1184-NodeServerTest-8575934/.npmrc"
   npm ERR! node v6.3.1
   npm ERR! npm  v3.10.3
   npm ERR! No compatible version found: fs@3.10.3
   npm ERR! Valid install targets:
   npm ERR! 0.0.2, 0.0.0
   npm ERR!
   npm ERR!
   npm ERR! If you need help, you may report this error at:
   npm ERR!     <https://github.com/npm/npm/issues>
   npm ERR! Please include the following file with any support request:
   npm ERR!     /tmp/build_7f369635973e963166afa93b918df0b4/Rocket1184-NodeServerTest-8575934/npm-debug.log

起初我以为是自己的版本写的不对,就一再的修改fshttp的版本号,从3.10.33.x再到>=0.0.1,依旧构建失败。
一直构建不过,肯定是哪里出了问题。于是来看看自己本地的这些模块的版本号:

$ npm ls
node-server-test@1.0.0 D:\Documents\GitHub\NodeServerTest
`-- (empty)

这里面的模块是空的!!!
废话,什么都没装,当然是空的。
我立马在package.json里面注释掉了这些东西(VSCode里面潇洒的一个Ctrl+/):

// "dependencies": {		
//   "fs": "3.x",		
//   "http": "3.x"		
// },

好了,commitpushdeploy,纳尼!!居然又报错了!!!

-----> Node.js app detected
parse error: Invalid numeric literal at line 12, column 5
 !     Unable to parse package.json
-----> Build failed

啊,JSON里面不能加注释啊。。。。好了,删掉,重跑,总算成功了。

仓库地址

GitHub仓库:BlogNode

主仓库,以后的代码都在这里更新。

HerokuApp:rocka-blog-node

上面GitHub仓库的实时构建结果。

posted @ 2016-08-13 17:02  Rocket1184  阅读(2386)  评论(2编辑  收藏  举报