Node学习笔记(一)

1、关于npm

npm是一个包管理器,她可以自动管理包的依赖。

  • 文件夹中的package.json一般通过npm安装:

    npm init

    然后随意填写相关信息就可以自动在文件夹下面生成一个package.json依赖管理件。当项目部署时,就不必将node_modules目录也上传到

    服务器服务器在拿到我们的项目时,只需要执行 npm install,则 npm 会自动读取package.json 中的依赖并安装在项目的 node_modules 下面,然后程序就可以在服务器上跑起来了。

  • 安装依赖一般用:

    $npm install express –save

    注:express可以用其他依赖名代替,也可以一次同时安装多个依赖,只需将依赖名用空格隔开即可。

2、关于req.query&req.body&req.param()&req.params
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
- req.body(获取表单的参数)
// POST user[name]=tobi&user[email]=tobi@learnboost.com
req.body.user.name
// => "tobi"
- req.params(这是一个数组对象,命名过的参数会以键值对的形式存放)
// GET /user/tj
req.params.name
// => "tj"
app.post('/user/signup/:userid',function(req,res) {
req.params.userid;
})
- req.query(这是一个解析过的请求参数对象)
// GET /search?q=tobi+ferret
req.query.q
// => "tobi ferret"
// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
req.query.order
// => "desc"
- req.param()(req.query、req.body、以及req.params获取参数的三种方式的封装)
// POST name=tobi
app.post('/user?name=tobi',function(req,res){
req.param('name');
// => "tobi"
})
// ?name=tobi
req.param('name')
// => "tobi"
// /user/tobi for /user/:name
req.param('name')
// => "tobi"
3、关于回调函数

​ 即给某个方法传递了一个函数,这个方法在有事件发生时调用这个函数来进行回调。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var http = require('http');
var url = require('url');
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log('Request ' + pathname + ' received.');
route(handle, pathname, response, request);
}
http.createServer(onRequest).listen(8888);
console.log('Server has started.');
}
exports.start = start;

其中,onRequest即为回调函数。

4、关于URL

http://localhost:8888/start?foo=bar&hello=world 中:

url.parse(string).pathname: /start

url.parse(string).query: foo=bar&hello=world

5、关于host = server.address().address
1
2
3
4
5
6
var server = app.listen(3000, '127.0.0.1', function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://' + host + ':' + port);
});

当app.listen中未指明host时(host被忽略时),host返回值为(::),即接受任意IPv6地址,或者返回(0.0.0.0),即任意IPv4地址。所以要想host返回值为localhost或其他指定的IP地址。app.listen中应写为app.listen(3000, ‘127.0.0.1’, function ()…)。

6、关于中间件函数
1
2
3
4
5
6
7
function(req, res, next) {}:中间件函数
get:HTTP请求
req:请求对象,中间件函数的 HTTP 请求自变量
res:响应对象,中间件函数的 HTTP 响应自变量
next():应用程序的请求/响应循环中的下一个中间件函数,中间件函数的回调自变量。
调用此函数时,将调用应用程序中的下一个中间件函数。调用 next() 函数将请
求传递到堆栈中的下一个中间件函数
  • 中间件函数的装入

    app.use(myLogger);

    中间件函数的装入很重要,先装入的中间件函数首先被执行。