在Mac OS下使用Node.js的简单教程

2020-06-17 05:49:36易采站长站整理

 


$ http-console

node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: require.paths is removed. Use node_modules folders, or the NODE_PATH environment variable instead.
at Function. (module.js:378:11)
at Object. (/usr/local/lib/node_modules/http-console/bin/http-console:6:8)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:40)

很麻烦,我们还需要手工编辑 /usr/local/lib/node_modules/http-console/bin/http-console 文件,然后删除下面这一行:
 
require.paths.unshift(path.join(__dirname, ‘..’, ‘lib’));

现在 http-console 就可以启动了,无需任何参数,它将连接到 http://localhost:8080 ,如果你需要指定服务器和端口,把它作为第一个参数传递给 http-console 即可。

请注意我们这里使用了 json 命令用来设置正确的 content-type:
 


$ http-console http://127.0.0.1:8000
The "sys" module is now called "util". It should have a similar interface.
> http-console 0.6.1
> Welcome, enter .help if you're lost.
> Connecting to 127.0.0.1 on port 8000.

http://127.0.0.1:8000/> json
http://127.0.0.1:8000/>

访问 REST 服务

在 http-console 中,要执行 GET 请求只需要输入 GET /bookmarks 即可:
 


http://127.0.0.1:8000/> GET /bookmarks
HTTP/1.1 200 OK
Date: Sun, 01 Apr 2012 17:23:27 GMT
Server: journey/0.4.0
Content-Type: application/json;charset=utf-8
Content-Length: 16
Connection: keep-alive

{
bookmarks: []}

你也可以使用 JSON 的片段来执行 POST 请求:
 


http://127.0.0.1:8000/> POST /bookmarks
... { "url": "http://nodejs.org" }
HTTP/1.1 200 OK
Date: Thu, 05 Apr 2012 11:45:55 GMT
Server: journey/0.4.0
Content-Type: application/json;charset=utf-8
Content-Length: 91
Connection: keep-alive

{
bookmark: {
_id: 'WD-G-1',
resource: 'Bookmark',
url: 'http://nodejs.org'
}
}

然后再次执行 GET 请求,你就可以看到新插入的数据了:
 


http://127.0.0.1:8000/> GET /bookmarks
HTTP/1.1 200 OK
Date: Sun, 01 Apr 2012 17:23:27 GMT
Server: journey/0.4.0
Content-Type: application/json;charset=utf-8
Content-Length: 16
Connection: keep-alive

{
bookmarks: [
{
_rev: '1-cfced13a45a068e95daa04beff562360',