Node.js Express框架

Express 简介

        Express是一个简洁而灵活的node.js Web因故用框架,提供了一系列强大特性帮助你创建各种Web应用,和丰富的HTTP工具。使用Express可以快速地搭建一个完整功能的网站

        特性:

可以设置中间件来响应HTTP请求。

定义了路由表用于执行不同的HTTP请求动作。

可以通过像模版传递参数来动态渲染HTML页面

安装 Express

npm install express --save

request和result对象

Request 对象 - request 对象表示 HTTP 请求,包含了请求查询字符串,参数,内容,HTTP 头部等属性。常见属性有:

  1. req.app:当callback为外部文件时,用req.app访问express的实例

  2. req.baseUrl:获取路由当前安装的URL路径

  3. req.body / req.cookies:获得「请求主体」/ Cookies

  4. req.fresh / req.stale:判断请求是否还「新鲜」

  5. req.hostname / req.ip:获取主机名和IP地址

  6. req.originalUrl:获取原始请求URL

  7. req.params:获取路由的parameters

  8. req.path:获取请求路径

  9. req.protocol:获取协议类型

  10. req.query:获取URL的查询参数串

  11. req.route:获取当前匹配的路由

  12. req.subdomains:获取子域名

  13. req.accpets():检查请求的Accept头的请求类型

  14. req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages

  15. req.get():获取指定的HTTP请求头

  16. req.is():判断请求头Content-Type的MIME类型

Response 对象 - response 对象表示 HTTP 响应,即在接收到请求时向客户端发送的 HTTP 响应数据。常见属性有:

  1. res.app:同req.app一样

  2. res.append():追加指定HTTP头

  3. res.set()在res.append()后将重置之前设置的头

  4. res.cookie(name,value [,option]):设置Cookie

  5. opition: domain / expires / httpOnly / maxAge / path / secure / signed

  6. res.clearCookie():清除Cookie

  7. res.download():传送指定路径的文件

  8. res.get():返回指定的HTTP头

  9. res.json():传送JSON响应

  10. res.jsonp():传送JSONP响应

  11. res.location():只设置响应的Location HTTP头,不设置状态码或者close response

  12. res.redirect():设置响应的Location HTTP头,并且设置状态码302

  13. res.send():传送HTTP响应

  14. res.sendFile(path [,options] [,fn]):传送指定路径的文件 -会自动根据文件extension设定Content-Type

  15. res.set():设置HTTP头,传入object可以一次设置多个头

  16. res.status():设置HTTP状态码

  17. res.type():设置Content-Type的MIME类型

路由

        路由决定了由谁(指定脚本)去响应客户端请求。在HTTP请求中,我们可以通过路由提取出请求的URL以及GET/POST参数。接下来我们扩展 Hello World,添加一些功能来处理更多类型的 HTTP 请求。

通过不同的url地址访问不同的页面 需要指定到路由中 "路由地址"

// 引入模块  须先使用npm进行下载
const express = require("express");
// 实例化
const app = express();
// 调用GET方法;
app.get("/index", function (req, res) {
  //   发送请求
  res.send("请求成功 GET");
});
app.post("/order", function (req, res) {
  //   发送请求
  res.send("请求成功 POST");
});
//可写正则
app.delete("/li*st", function (req, res) {
  //   发送请求
  res.send("请求成功 DELETE");
});
// 监听
app.listen(8081);
console.log("服务器连接成功:http://127.0.0.1:8081");

静态文件

        Express 提供了内置的中间件 express.static 来设置静态文件如:图片, CSS, JavaScript 等。

        你可以使用 express.static 中间件来设置静态文件路径。例如,如果你将图片, CSS, JavaScript 文件放在 public 目录下,

const express = require("express");
let app = express();
// static中间件
app.use(express.static("public"));
app.get("/", function (req, res) {
  res.send("hello world");
});
app.listen(8080);
console.log("服务器连接成功:http://127.0.0.1:8080");

GET方法

html文件:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="sendName" method="get">
        姓:<input type="text" name="first_name"><br>
        名:<input type="text" name="last_name"><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

js文件:

// 引入模块
const express = require("express");
let app = express();
​
app.get("/index", function (req, res) {
  //   console.log(__dirname);
  // 获取文件的路径
  res.sendFile(__dirname + "/getName.html");
});
app.get("/sendName", function (req, res) {
  //   console.log(req.query);  内置方法
  // 接收数据
  let obj = {
    firstName: req.query.first_name,
    lastName: req.query.last_name,
  };
  // 设置编码格式
  res.writeHead(200, { "Content-Type": "text/plain;charset= utf-8" });
  // 序列化并输出
  //   res.end(JSON.stringify(obj));
  res.end(`姓名:${obj.firstName}${obj.lastName}`);
});
// 设置监听端口号
app.listen(8080);

Ps.

对象 转换为 字符串——序列化——JSON.stringify()

字符串 转换为 对象——反序列化——JSON.parse()

POST方法

body-parser中间件

html文件:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="postName" method="post">
        姓:<input type="text" name="first_name"><br>
        名:<input type="text" name="last_name"><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

js文件:

// 引入模块
const express = require("express");
// 通过body-parser模块
const bodyParser = require("body-parser");
let app = express();
// 编码解析中间件/请求体
let codeParser = bodyParser.urlencoded({ extended: false });
app.get("/index", function (req, res) {
  res.sendFile(__dirname + "/postName.html");
});
app.post("/postName", codeParser, function (req, res) {
  let obj = {
    firstName: req.body.first_name,
    lastName: req.body.last_name,
  };
  res.end(JSON.stringify(obj));
});
app.listen(8080);

文件上传

multer中间件

终端安装multer:npm i multer

请求方式必须为post,form表单必须设置enctype="multipart/form-data"

html文件:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" size="50" name="image"><br>
        <input type="submit" value="上传文件">
    </form>
</body>
</html>

js文件:

// 引入模块  终端安装multer
const express = require("express");
const multer = require("multer");
const fs = require("fs");
let app = express();
// 使用中间件
app.use(express.static("public"));
// multer中间件; 设置上传图片的文件夹
let upload = multer({ dest: "public/upload/" });
// 跳转到提交页
app.get("/", (req, res) => {
  res.sendFile(__dirname + "/getFile.html");
});
// 文件上传之后都会生成一个唯一的编码文件
// single(name值) 该方法接收单个上传的文件
// array(name值) 该方法接收多个上传文件
// 多个文件通过遍历files
app.post("/upload", upload.single("image"), (req, res) => {
  // fs.renname();
  //   console.log(req.file);
  //   获取文件的路径 及 文件名
  let oldName = req.file.destination + req.file.filename; //指定旧文件
  let newName = req.file.destination + req.file.originalname; //制定新文件
  //   设置响应头及编码级
  res.writeHead(200, { "Content-Type": "text/plain;charset=UTF-8" });
  //   通过fs模块更改文件名
  fs.rename(oldName, newName, (err) => {
    if (err) {
      res.end("上传失败");
    } else {
      res.end("上传成功");
    }
  });
});
// 监听8080端口
app.listen(8080);
console.log("服务器连接成功:http://127.0.0.1:8080");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值