NodeJS简易博客系统(七)express框架入门学习

一、安装及demo

如果已经装好webstorm,直接新建项目如下:

否则cd到项目目录下,使用npm install express --save即可完成安装。

demo:

var express=require('express'); /*引入 express*/
var app=new express(); /*实例化 express 赋值给 app*/
//配置路由 匹配 URl 地址实现不同的功能
app.get('/',function(req,res){
res.send('首页');
})
app.get('/search',function(req,res){
res.send('搜索');
//?keyword=华为手机&enc=utf-8&suggest=1.his.0.0&wq
})
app.get('/login',function(req,res){
res.send('登录');
})
app.get('/register',function(req,res){
res.send('注册');
})
app.listen(3000)
然后运行访问http://localhost:3000即可看到效果。

二、路由(routing)

路由(Routing)是由一个 URI(或者叫路径)和一个特定的 HTTP 方法(GET、 POST 等)
组成的,涉及到应用如何响应客户端对某个网站节点的访问。

1、简单路由配置

GET app.get("网址",function(req,res){   });
POST app.post("网址",function(req,res){   });
PUT app.put('/user', function (req, res) {   res.send('Got a PUT request at /user'); });
DELETE app.delete('/user', function (req, res) {   res.send('Got a DELETE request at /user'); }); 

2、动态路由配置

app.get("/user/:id",function(req,res){ var id = req.params["id"]; res.send(id); }); 

3、路由的正则匹配

app.get('/ab*cd', function(req, res) {   res.send('ab*cd'); });

4、路由里面获取 Get 传值 

/news?id=2&sex=nan 

app.get('/news, function(req, res) {    console.log(req.query); }); 

三、 托管静态文件 

1、如果你的静态资源存放在多个目录下面,你可以多次调用 express.static 中间件: 

app.use(express.static('public')); 

现在,public 目录下面的文件就可以访问了。 

http://localhost:3000/css/style.css 
http://localhost:3000/js/app.js 
http://localhost:3000/hello.html 

2、如果你希望所有通过 express.static 访问的文件都存放在一个“虚拟(virtual)”目 录(即目录根本不存在)下面,可以通过为静态资源目录指定一个挂载路径的方式来实现, 如下所示: 

app.use('/static', express.static('public'));   

现在,你就爱可以通过带有 “/static” 前缀的地址来访问 public 目录下 面的文件了。 

http://localhost:3000/static/css/style.css 
http://localhost:3000/static/js/app.js 
http://localhost:3000/static/hello.html 

四、Express 中间件 

Express 是一个自身功能极简,完全是由路由和中间件构成一个的 web 开发框架:从 本质上来说,一个 Express 应用就是在调用各种中间件。 
中间件(Middleware) 是一个函数,它可以访问请求对象(request object (req)), 响应对象(response object (res)), 和 web 应用中处理请求-响应循环流程中的中间件,一般 被命名为 next 的变量。 
中间件的功能包括: 

  • 执行任何代码。
  • 修改请求和响应对象。
  • 终结请求-响应循环。
  • 调用堆栈中的下一个中间件。 

如果我的 get、post 回调函数中,没有 next 参数,那么就匹配上第一个路由,就不会往下匹 配了。如果想往下匹配的话,那么需要写 next() 。

Express 应用可使用如下几种中间件: 

1. 应用级中间件 

app.use(function(req,res,next){  /*匹配任何路由*/     //res.send('中间件'); 
    console.log(new Date()); 
    next();  /*表示匹配完成这个中间件以后程序继续向下执行*/ 
}) 
app.get('/',function(req,res){ 
    res.send('根'); 
}) 
app.get('/index',function(req,res){ 
    res.send('首页'); 
}) 
 

2、路由中间件 

app.get("/",function(req,res,next){     console.log("1");     next(); }); 
app.get("/",function(req,res){        console.log("2"); }); 

3、 错误处理中间件 

app.get('/index',function(req,res){     res.send('首页'); }) 
/*中间件相应 404*/

app.use(function(req,res){    

  //res.render('404',{});

  res.status(404).render('404',{});

})

4. 内置中间件

//静态服务  index.html

app.use('/static',express.static("./static"));   /*匹配所有的路径*/ 

app.use('/news',express.static("./static"));   /*匹配所有的路径*/ 

5. 第三方中间件 

body-parser 中间件   第三方的   获取 post 提交的数据 
1.cnpm install body-parser --save 
 2.var bodyParser = require('body-parser') 
 3.设置中间件 
 //处理 form 表单的中间件 
 // parse application/x-www-form-urlencoded  app.use(bodyParser.urlencoded({ extended: false }));  form 表单提交的数据 
 // parse application/json  app.use(bodyParser.json());  提交的 json 数据的数据 
 4.req.body 获取数据 

五、获取 Get  Post 请求的参数 

● GET 请求的参数在 URL 中,在原生 Node 中,需要使用 url 模块来识别参数字符串。在 Express 中,不需要使用 url 模块了。可以直接使用 req.query 对象。 
● POST 请求在 express 中不能直接获得,可以使用 body-parser 模块。使用后,将可以用 req.body 得到参数。但是如果表单中含有文件上传,那么还是需要使用 formidable 模块。 

1、安装

npm install body-parser 

2.使用req.body 获取 post 过来的参数 

var express = require('express')

var bodyParser = require('body-parser')  

var app = express()  

// parse application/x-www-form-urlencoded  app.use(bodyParser.urlencoded({ extended: false }))  

 // parse application/json  

app.use(bodyParser.json())  

app.use(function (req, res) {   res.setHeader('Content-Type', 'text/plain')   res.write('you posted:\n') 
res.end(JSON.stringify(req.body, null, 2)) }) 


 总结,其实小项目用到的就是路由,获得值传递,响应界面,cookies存储等等。当然,更深层次的学习还有后续。

猜你喜欢

转载自blog.csdn.net/weixin_42363997/article/details/83306623