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 头部等属性。常见属性有:

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.accpets():检查请求的Accept头的请求类型

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.send():传送HTTP响应

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

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

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

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");

制作一个简易的商品界面

html文件:

<!DOCTYPE html>
<html lang="en">

<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>
    <style>
        p {
            font-size: 25px;
        }

        input {
            width: 250px;
            height: 25px;
        }

        #Butto {
            margin-left: 50px;

        }
    </style>
</head>

<body>
    <p><b>编辑商品</b></p>
    <form action="/porcess_post" method="post">
        <table>
            <tr>
                <td><b>名称</b></td>
                <td><input type="text" name="Name" placeholder="xx笔记本电脑xx英x尔酷xxx"></td>
            </tr>

            <tr>
                <td><b>市场价</b></td>
                <td><input type="number" name="Market"></td>
            </tr>
            <tr>
                <td><b>售价</b></td>
                <td><input type="text" name="price"></td>
            </tr>
            <tr>
                <td style="vertical-align:text-top;"><b>产品介绍</b></td>
                <td><textarea name="Product" cols="33" rows="10"></textarea></td>
            </tr>
            <tr>
                <td><b>是否在线</b></td>
                <td><input type="checkbox" style="width: 15px;" name="Online"></td>
            </tr>
            <tr>
                <td><b>添加时间</b></td>
                <td><input type="date" name="Time"></td>
            </tr>
            <tr>
                <td><b>商品类型</b></td>
                <td>
                    <select  id="" style=" width: 250px;
                    height: 25px;" name="type">
                        <option value="笔记本">笔记本</option>
                        <option value="平板电脑">平板电脑</option>
                        <option value="手机">手机</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align:center;"><input type="submit"
                        style="width:80px; background-color: #396BA3; color: white;"></td>
                <td></td>
            </tr>

        </table>

    </form>
</body>

</html>

js文件:

const express = require('express');
const app = express();
const bodyparser = require('body-parser');
const parser = bodyparser.urlencoded({ extended: false });
app.get('/dome', function (req, res) {
    console.log(__dirname);
    res.sendFile(__dirname + '/one.html');
})

app.post('/porcess_post', parser, function (req, res) {
    let obj = {
        Name: req.body.Name,
        Market: req.body.Market,
        price: req.body.price,
        Product: req.body.Product,
        Online: req.body.Online,
        Time: req.body.Time,
        type: req.body.type,
    }
    // res.writeHead(200, { 'Content-type': 'text/plain;charset=utf-8' })
    // // 将对象序列化成字符串
    // res.end(JSON.stringify(obj))
    console.log(obj);
    // console.log(JSON.stringify(obj))
    res.writeHead(200, { 'Content-Type': 'text/html; charset=UTF-8' })
    res.end(`名称:${obj.Name}
    市场价:${obj.Market}
    售价:${obj.price}
    产品介绍:${obj.Product}
    是否在售:${obj.Online}
    时间:${obj.Time}
    类别:${obj.type}`);

})

app.listen(1234);

效果图

 

 输出结果:

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值