使用Express 框架快速搭建web应用

使用Express 框架快速搭建web应用

安装express 框架

  • step.1 安装node.js 环境,默认带npm(略)
  • step.2 安装express框架
$ mkdir my_express
$ npm init
$ cnpm install express --save
$ cnpm install body-parser --save
$ cnpm install cookie-parser --save
$ cnpm install multer --save

注意:
body-parser - node.js 中间件,用于处理 JSON, Raw, Text 和 URL 编码的数据。
cookie-parser - 这就是一个解析Cookie的工具。通过req.cookies可以取到传过来的cookie,并把它们转成对象。
multer - node.js 中间件,用于处理 enctype=“multipart/form-data”(设置表单的MIME编码)的表单数据。

  • step.3 创建目录结构
-my_express
    |---- node_modules
    |---- public
    |    |---- logo.jpg
    |    |---- index.html
    |
    |---- index.js
  • step.4 开始开发index.js
var express = require('express');
var App = new express();

// 声明public目录为 静态资源目录(js,css,jpg等)
App.use('/pub', express.static('public'));

App.get('/', function (req,res) {
	res.send('Hello World');
});

// get 方法加载模板文件
App.get('/index.html', function (req, res) {
   res.sendFile( __dirname + "/public/" + "index.html" );
})

// get 获取参数
App.get('/user', function (req,res) {
	   // 输出 JSON 格式
   var response = req.query;
   console.log(response);
   res.end(JSON.stringify(response));

});

// post 获取参数
var bodyParser = require('body-parser');
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false });

App.post('/process_post', urlencodedParser, function (req,res) {
	res.send(req.body);
});

// 获取cookies
var cookieParser = require('cookie-parser');
App.use(cookieParser());

App.get('/cookies', function (req,res) {
	console.log(req.cookies);
	res.end('read cookies');
});

// 启动监听服务
var server = App.listen(8888, function () {
	var host = server.address().address;
	var port = server.address().port;
	console.log("应用,htpp://%s:%s", host ,port);
});
<html>
<body>
<h3>get</h3>
<form action="/user" method="GET">
First Name: <input type="text" name="first_name">  <br>
 
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>

<h3>post</h3>

<form action="/process_post" method="POST">
First Name: <input type="text" name="first_name_post">  <br>
 
Last Name: <input type="text" name="last_name_post">
<input type="submit" value="Submit">
</form>

<h3>upload file</h3>
<form action="/file_upload" method="post" enctype="multipart/form-data">
<input type="file" name="image" size="50" />
<br />
<input type="submit" value="上传文件" />
</form>

</body>
</html>

关键注解

关键代码 功能
App.use(’/pub’, express.static(‘public’)) 声明定义public目录为静态资源,使外部可直接通过http访问
res.sendFile( __dirname + “index.html” ); 把某个模板文件转发回浏览器
req.query 获取URL中的所有参数
req.body 获取body中的所有参数(注意,需要使用require('body-parser') 否则获取不了)

request 和 response 对象的具体介绍:

  • Request 对象 - request 对象表示 HTTP 请求,包含了请求查询字符串,参数,内容,HTTP 头部等属性。常见属性有:
属性 说明
req.app 当callback为外部文件时,用req.app访问express的实例
req.baseUrl 获取路由当前安装的URL路径
req.body / req.cookies 获得「请求主体」/ Cookies
req.fresh / req.stale 判断请求是否还「新鲜」
req.hostname / req.ip 获取主机名和IP地址
req.originalUrl 获取原始请求URL
req.params 获取路由的parameters
req.path 获取请求路径
req.protocol 获取协议类型
req.query 获取URL的查询参数串
req.route 获取当前匹配的路由
req.subdomains 获取子域名
req.accepts() 检查可接受的请求的文档类型
req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages 返回指定字符集的第一个可接受字符编码
req.get() 获取指定的HTTP请求头
req.is() 判断请求头Content-Type的MIME类型
  • Response 对象 - response 对象表示 HTTP 响应,即在接收到请求时向客户端发送的 HTTP 响应数据。常见属性有:
属性 说明
res.app 同req.app一样
res.append() 追加指定HTTP头
res.set() 在res.append()后将重置之前设置的头
res.cookie(name,value [,option]) 设置Cookie
opition domain / expires / httpOnly / maxAge / path / secure / signed
res.clearCookie() 清除Cookie
res.download() 传送指定路径的文件
res.get() 返回指定的HTTP头
res.json() 传送JSON响应
res.jsonp() 传送JSONP响应
res.location() 只设置响应的Location HTTP头,不设置状态码或者close response
res.redirect() 设置响应的Location HTTP头,并且设置状态码302
res.render(view,[locals],callback) 渲染一个view,同时向callback传递渲染后的字符串,如果在渲染过程中有错误发生next(err)将会被自动调用。callback将会被传入一个可能发生的错误以及渲染后的页面,这样就不会自动输出了。
res.send() 传送HTTP响应
res.sendFile(path [,options] [,fn]) 传送指定路径的文件 -会自动根据文件extension设定Content-Type
res.set() 设置HTTP头,传入object可以一次设置多个头
res.status() 设置HTTP状态码
res.type() 设置Content-Type的MIME类型
发布了88 篇原创文章 · 获赞 3 · 访问量 5518

猜你喜欢

转载自blog.csdn.net/youlinhuanyan/article/details/100315664