node学习笔记二

撰写于 2017-07-05 修改于 2017-07-05

http/fs/get/post

用户注册、登录

接口:

/user?act=reg&user=aaa&pass=123456
{“ok”: false, “msg”: “原因”}

/user?act=login&user=aaa&pass=123456
{“ok”: true, “msg”: “原因”}


对文件访问:

http://localhost:8080/1.html
http://localhost:8080/ajax.js
http://localhost:8080/1.jpg

对接口访问:

http://localhost:8080/user?act=xx
http://localhost:8080/news?act=xxx


模块化

1.系统模块:http、querystring、url
2.自定义模块
3.包管理器

系统模块:

www.baidu.com->
getServer

Crypto 加密
Events 事件
Net 网络操作
OS 操作系统信息
Path 处理文件路径
Stream 流操作
Timers 定时器
ZLIB 压缩

require


/usr/tmp/aaa/a.txt
/usr/tmp/aaa/
a.txt
.txt


1.模块组成
2.npm
3.发布自己的模块

引入自己的模块——./ ?
对外输出东西——必须加给exports


exports.xxx=??;
exports.xxx=??;
exports.xxx=??;

module.exports={
xxx: ??,
xxx: ??,
xxx: ??
};


require——引入其他模块
exports——输出
module——批量输出


1.自己的模块
require
module
exports

2.引入模块 ./ ?
3.”.js”可选


npm:NodeJS Package Manager(NodeJS包管理器)

1.统一下载途径
2.自动下载依赖


npm install xxx
npm uninstall xxx


node_modules——放模块


./
不加./ 必须放在node_modules里面


require

1.如果有”./“
从当前目录找

2.如果没有”./“
先从系统模块
再从node_modules找


自定义模块统一,都放到node_modules里面


1.模块里面
require——引入
exports——输出
module.exports——批量输出

2.npm
帮咱们下载模块
自动解决依赖

3.node_modules
模块放这里


npm init
npm publish
npm –force unpublish


express框架

1.安装

2.配置

3.接收请求

4.响应


非侵入式
req

原生:
res.write();
res.end();

express:
*res.send();
res.write();
res.end();


express保留了原生的功能,添加了一些方法(send),增强原有的功能


//1.创建服务
var server=express();

//2.监听
server.listen(8080);

//3.处理请求
server.use(‘地址’, function (req, res){
});


3种方法:
.get(‘/‘, function (req, res){});
.post(‘/‘, function (req, res){});
.use(‘/‘, function (req, res){});


中间件


/login?user=xxx&pass=xxx
=>{ok: true/false, msg: ‘原因’}


express框架:
1.依赖中间件
2.接收请求
get/post/use
get(‘/地址’, function (req, res){});
3.非破坏式的
req.url
4.static用法
const static=require(‘express-static’);
server.use(static(‘./www’));


Express:

1.数据:GET、POST
2.中间件:使用、写、链式操作


GET-无需中间件
req.query

POST-需要”body-parser”
server.use(bodyParser.urlencoded({}));

server.use(function (){
req.body
});


链式操作:


1.GET、POST
req.query

server.use(bodyParser.urlencoded({limit: }));
server.use(function (req, res, next){
req.body
});

2.链式操作
server.use(function (req, res, next){});
server.get(‘/‘, function (req, res, next){});
server.post(function (req, res, next){});

next——下一个步骤
next();

server.use(‘/login’, function (){
mysql.query(function (){
if(有错)
res.emit(‘error’);
else
next();
});
});

3.中间件(body-parser)、自己写中间件
next();

server.use(function (req, res, next){
var str=’’;
req.on(‘data’, function (data){
str+=data;
});
req.on(‘end’, function (){
req.body=querystring.parse(str);
next();
});
});

Site by yophy using Hexo & Random

Hide