full-stack web front-end development _node source notes in class [Ashoka]

A, NodeJS simple review
NodeJS is a modular development, with many built-in module. HTTP server means for building. FS means for manipulating files and folders. URL converting means for URL strings and URL object. QueryStrings module for parsing query on the URL.

1.1 HTTP module

1.2 FS module

读取文件

fs.readFile(path, callback)

path: 被读取的文件地址  是一个路径 该路径属于后端路径

callback: 读取完成之后的回调函数  

该回调函数有两个参数

err: 读取过程中可能出现的异常。 如果没有异常,err是null。如果有,err是异常对象。

data: 是一个buffer数据,表示被读取到的文件信息。

创建文件/追加文件内容

fs.appendFile(path, data, callback);

path: 被创建/追加的文件所在地 是一个后端路径

data: 被创建/追加的文件内容

callback: 执行完毕之后执行的回调函数

该回调函数有一个参数

err: 创建/追加过程中可能出现的异常

删除文件  

fs.unlink(path, callback);

path: 被移除的文件的地址 是一个后端路径

callback: 移除过程中可能会出现的异常

创建文件夹   

fs.mkdir(path, callback);

path: 被创建出来的文件夹 (只创建最后一层)

callback: 创建过程完成之后的回调函数

err: 创建过程中可能出现的异常

移除文件夹

fs.rmdir(path, callback);

path: 被移除的文件夹的路径 (只能移除空的文件夹)

callback: 移除过程之后回调函数

err: 移除过程中可能出现的异常

读取文件夹

fs.readdir(path, callback);

path: 被读取的文件夹路径

callback: 读取之后执行的回调函数

err: 读取过程中可能出现的异常

arr: 读取成功之后,目标文件夹内每一个文件和文件夹的名称的数组

判定目标状态

fs.stat(path, callback);

path: 被判定的目标路径

callback: 判定完成的回调函数

err: 判定过程中可能出现的异常

stat: 状态对象

isDirectory method returns a Boolean value of true if the folder is false otherwise

All of the above methods, there is a method xxxSync

For example: readFile () is a synchronous method of asynchronous method readFileSync

readdir () is a synchronous method of asynchronous method readdirSync

unlink () is an asynchronous method unlinkSync ......

Asynchronous method has a return value, accepted by the callback function returns the contents of the parameter

Synchronization method has a return value returned by the content receiving variable

readFile(xxx, function(err, data) {

Content data is read to file

})

var data = readFileSync(xxx);

data is read into the contents of the file

1.3 移除非空目录
1 // 定义函数

2 function del(path) {

3  console.log("进入" + path)

4  // path指的是一个目录的路径

5  // 当前del函数 用于删除非空目录 非空目录内部也有可能存在非空目录 所以又要调用del 也就是自己调用自己

6  // 读取path文件夹

7  var arr = fs.readdirSync(path);

8  // 循环

9  for(var i = 0; i < arr.length; i++) {

10   var stat = fs.statSync(path + "/" + arr[i]);

11   if(stat.isDirectory()) {

12    del(path + "/" + arr[i]);

13   } else {

14    console.log("删除文件" + path + "/" + arr[i])

15    fs.unlinkSync(path + "/" + arr[i])

16   }

17  }

18  console.log("删除" + path)

19  // 把path本身也删掉

20  fs.rmdirSync(path)

21 }

Two, Express
2.1 Introduction
Express is a back-end third-party modules

Mainly used to build server.
full-stack web front-end development _node source notes in class [Ashoka]
2.2 Installation

npm: All uploaded the module package management system can be placed on npm

Download: express

full-stack web front-end development _node source notes in class [Ashoka]

Download completed:

full-stack web front-end development _node source notes in class [Ashoka]

2.3 build server

1 // 引入express

2 var express = require("express");

3 // 搭建服务器

4 var app = express();

5 // 监听服务器

6 app.listen(3000);

Note: express did not make any changes to the properties and methods native to it just adds content

2.4 Routing

普通路由:

app.verbs(pathName, callback);

pathName: 是一个url中的pathName部分

callback: 是对应的处理函数

req: 请求对象

res: 响应对象

next: 放行函数

verbs的类型: get 、 post、 put、 delete

app.get:

1 app.get("/index.html", function(req, res, next) {

2 

3 })

app.post:

1 app.post("/regist", function() {

2    

3 })
路由对象:

express内置了一个路由对象构造函数 express.Router

使用:

1 var route = express.Router();

2 route.get("xxx", function(req, res, next) {

3   

4 })

5 route.get("xxxx", function(req, res, next) {

6 })

7 // 使用该路由对象  当使用之后,路由对象身上所有的配置将生效。

8 app.use(route)

2.5 Routing Configuration wording

1 纯字符串

1 // 普通字符串

2 app.get("/a", function(req, res) {

3   console.log("a");

4 })
2 伪正则表达式

1 app.get("/a?", function(req, res) {

2  // ?在正则表达式中 表示可以有一个 可以没有

3  // 当前路由匹配的是 / 或者 /a

4  console.log("伪正则表达式")

5 })
3 正则表达式

1 app.get(/^\/\w+$/, function(req, res) {

2  console.log("正则表达式")

3 })
4 特殊url

1 app.get("/aaa:a/bbb:b", function(req, res) {

2  // 假如 用户使用的url是 /aaa123/bbb234

3  // 那么 当前的路由会将aaa123 和 bbb234分别获取到  

4  // 然后与当前的表达式匹配

5  // aaa:a => aaa123

6  // bbb:b => bbb234

7  // 其中从冒号开始分割 aaa => aaa   a => 123

8  // bbb => bbb b => 234

9  // 将a和b组成一个对象 挂载req身上作为params属性存在

10  console.log(req.params)

11 })

2.6 Static middleware
if each route must be configured, static files how to do? Do you want a one write configuration?

A: The use of static middleware

1 var express = require("express");

2 

3 var app = express();

4 

5 // 使用静态中间件

6 // 静态中间件是express的唯一内置中间件

7 app.use(express.static("./static"))

8 // 在访问./static文件夹下的文件时,不需要在url上写static这一层

9 

10 app.listen(3000);

At this point, any static files in the directory can be accessed directly to

2.7 Get get request data
express the url resolved in advance, wherein, a query portion is formatted into the body as an object mount req query exists.

Front-end url submission:

1 http://localhost:3000/login?username=张三

Get the back end of req.query:

1 {username: "San"}

2.8 post acquisition request data
and get different post may carry more data, it will then express post request processing section separately, to extract out to make a plug.

Plug-name: body-parser

How to download: npm install body-parser

full-stack web front-end development _node source notes in class [Ashoka]

use:

1 引入: var body_parser = require("body-parser");

2 配置: app.use(body_parser.urlencoded({extended: false}));

At this time, the post may be any route, using req.body obtain data which are submitted.

2.9 template
and the template with the express commonly used are two: jade and ejs

Which, jade template requires the use of spaces to indent. Template difference and underscore our previous templates as well as our custom large.

ejs, the difference is small. We chose ejs.

Download ejs:

1 npm install ejs

carry out:
full-stack web front-end development _node source notes in class [Ashoka]

Use: the need to introduce when in use. Because express has helped us introduced.

Default Folder: views

渲染模板:

1 res.render("login.ejs", {

2  username: username,

3  children: [

4   {

5    username: "王二小"

6   },

7   {

8    username: "王小二"

9   },

10   {

11    username: "张三"

12   }

13  ]

14 })

render method

The first parameter is the path to be rendered by default template from looking at views

The second parameter is the dictionary object rendering template needed

Three, Cookie
3.1 from registration initiation
suppose you have a router, connect the phone to the router, it is the "login" state. Disconnect the phone is a non-logged.

如果对应到网站上,因为HTTP协议的无状态。导致没有办法保持住连接。从理论上来说,是无法实现登录。

所以,有人想了一个办法。

HTTP第一次登录, 在响应头中设置一个标记。该标记上有一些信息。将用户的姓名和密码设置在该标记上返回给前端。

当浏览器接受到本次响应,查看到该标记,于是就把数据存储起来。之后每一次发往该服务器的请求都会携带该数据。

这个标记就叫做cookie。

存储在浏览器端。

登录之前:

full-stack web front-end development _node source notes in class [Ashoka]

登录之后:
full-stack web front-end development _node source notes in class [Ashoka]

访问其他页面:
full-stack web front-end development _node source notes in class [Ashoka]

3.2 设置cookie
任何服务器都可以设置cookie,不仅仅是node服务器。

如果是原生node服务器,那么请使用res.setHeader来设置cookie

如果是express服务器,那么请使用 res.cookie();


res.cookie(key,value, options)

key: cookie的键名

value: cookie的键值

options: 对当前cookie的配置对象

domain: 表示主域 默认是服务器的域名

expires: 表示过期日期 默认没有 也就是关闭页面即过期

maxAge: 表示过期毫秒值  值默认为0 也就是关闭页面即过期

path: 表示在哪个路径下生效 默认是/ 也就是全路径下都生效

httpOnly: 表示只能服务器设置cookie

 res.cookie("username", username);

四、 Session
cookie已经可以保持登录状态了。但是使用的方式有缺陷。

明文传递敏感信息。这是不可取的。

所以又有了session。

第一次用户登录的时候,将信息传递给后台,服务器将数据存入session,并返回一个随机id。将该id放入响应头中(其实就是放入cookie中),返回给前端。

当浏览器接受到cookie,存储数据。

以后浏览器每一次登录的时候都会把id带到服务器上,服务器可以根据id去session中查询得到本次连接的用户是谁。

同样的任何服务器都可以设置session。

express帮助我们简化了这个过程。

需要借助 express-session 模块

下载:

1 npm install express-session

配置:

1 // 引入express-session

2 var session = require("express-session");

3 // 配置session

4 app.use(session({

5 secret: "dsoifjewaoifjoiewajfoiewajfoijewafoijewaoifjewao",

6 resave: false,

7 saveUninitialized: false

8 }))

Use: Any route information is read using req.session.xxx setting information using req.session.xxx =

No public concern "icketang", the front end for the latest information, learning materials

B war search for "Ashoka classroom training professional front-end" front-end watch free video and project combat

Guess you like

Origin blog.51cto.com/14337100/2419779