nodejs入门之Express进阶

Express进阶

一.Request

Request 对象表示 HTTP 请求。Express 在现在基础上做了一层封装添加了一些简单好用的属性与方法。

1.req.query:获取query参数(问号传参)

const express = require('express');

const app = express();
app.get('/', (req, res) => {
    //http://localhost:3000
    console.log(req.query);//返回一个对象 {}

    //http://localhost:3000?username=zhangsan&age=18
    console.log(req.query);//返回一个对象 { username: 'zhangsan', age: '18' }
    res.send(req.query);
});

2.req.body:获取 body 参数(请求体传参,需要配置 express.json() 与 express.urlencoded())

const express = require('express');

const app = express();
//处理json格式 的请求体
app.use(express.json());
//处理 x-www-form-xvasdfasdfasdf 这种格式
app.use(express.urlencoded({
    extended: true
}));

app.post('/getBody', (req, res) => {
    console.log(req.body);//undefined 因为没有设置中间件
    console.log(req.body.username);//设置中间之后可以获取
    console.log(req.body.age);//设置中间之后可以获取
    res.send(req.body);//设置中间之后返回的是对象{ username: 'zhangsan', age: '18' }
});

3.req.params:获取 params 参数(动态路径传参)

//http://localhost:3000/user/app   app
//http://localhost:3000/user/web   web
//http://localhost:3000/user/moblie moblie

// 冒号后面的可以当做变量  动态路由
app.get('/users/:userRoute', (req, res) => {
    //    我们要想让这三个路径都能进来就要做下区分
    //req.params=>{userRoute:'app'}
    console.log(req.params);
    res.send(req.params);
});

//http://localhost:3000/user/x/app/y
//http://localhost:3000/user/1234/app/34444
//这种长路径,含有变量的
app.get('/user/:userId/app/:bookId', (req, res) => {
    console.log(req.params);
    res.send(req.params); //{ userId: '1234', bookId: '34444' }
});

4.req.cookies:获取 cookies 数据(需要配置 cookie-parser )

获取cookies ,需要第三方 cookie-parser 模块的支持

1.项目下安装cookie-parser模块

$ npm install cookie-parser

2.项目中引入cookie-parser

const cookieParser=require('cookie-parser');

3.通过app.use来调用它

app.use(cookieParser);
const express = require('express');

//req.cookies 在项目中引入cookie-parser
const cookieParser = require('cookie-parser');

const app = express();

// req.cookies 需要app.use来调用
app.use(cookieParser());

// 获取cookies, 需要第三方 cookie-parser 模块的支持
// 1. 项目下安装 cookie-parser 模块
//      npm install cookie-parser
// 2. 项目中 引入 cookie-parser 
// 3. 通过 app.use 来调用它
// GET http://localhost:3000/getCookie
app.get('/', (req, res) => {
    console.log(1234);
});
//获取cookie
app.get('/getCookie', (req, res) => {

    console.log(req.cookies);//{} 因为当前没有设置cookie
    res.send(req.cookies);
});

// 设置 cookie 。使用 res.cookie(name, value [, options])
// GET http://localhost:3000/setCookie
app.get('/setCookie', (req, res) => {
    res.cookie("name", 'zhangsan');
    res.send('设置cookie成功');
});

// 浏览器的 cookie 是不需要主动去传递的,只要有发请求时都会自动携带在请求头中
app.get('hello', (req, res) => {
    res.cookie('name', 'zhangsan', {
        // 过期时间,单位毫秒  1s = 1000ms  20s = 20 * 1000
        maxAge: 1000 * 20
    });
    res.send('设置cookie成功');
});
// cookie 不光前端能设置,后端也能设置。
app.listen(3000, function () {
    console.log("服务启动成功");

});

5.req.get(field):获取指定的请求头数据

const express = require('express');

const app = express();

// req.get(field)  获取指定的请求头数据
app.get('/', (req, res) => {
    console.log(req.get("host"));//localhost:3000
    console.log(req.get("Host"));//localhost:3000
    res.status(500).send('hello');//返回设置http状态码
});

//重定向  redirect
app.get("/index", (req, res) => {
    //http://localhost:3000/index  =>  https://www.baidu.com
    res.redirect('https://www.baidu.com');
});

// GET http://localhost:3000/pc
/**
 * 需求,当用户是通过手机去访问这个地址时,直接重定向到mobile端
 * 
 * 关键点在于如何判断用户访问时使用的是电脑浏览器,还是手机浏览器
 *    根据 请求头中的 User-Agent 字段来判断即可
 * 
 */
app.get('/pc', (req, res) => {
    // 1. 获取到 User-Agent 字段的值
    let ua = req.get("User-Agent");
    // 转成小写,判断是否存在mobile字段
    if (ua.toLowerCase().indexOf('mobile') > -1) {
        //若存在,则是访问重定向到手机端
        res.redirect('/mobile');
        res.send("mobile");
    }
    else {
        //不存在则是pc端
        res.send("pc");
    }
});


app.get('/mobile', (req, res) => {
    res.send("mobile端");
});


app.listen(3000, () => {
    console.log("服务启动成功");
});

Request还有很多的方法可以去官网查看

更多

二.Response

Response 对象表示 HTTP 响应。Express 在现在基础上做了一层封装添加了一些简单好用的属性与方法。

1.res.send([body]):发送 HTTP 响应。body 参数可以是 Buffer 对象、String、Object、Array 类型

res.send("body");

//如果是Buffer对象,需要转为string输出
res.send(Buffer.toString());

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

app.get('/', (req, res) => {
    res.status(500).send('hello');//返回设置http状态码
});

3.res.json([body]):发送 HTTP 响应。JSON 格式
返回json格式的字符串,此方法完全可以使用 res.send() 替代

res.send([{ username:"zhangsan" }]);

4.res.redirect([status,] path):重定向到 path 路径,status 默认为 302**

//重定向  redirect
app.get("/index", (req, res) => {
    //http://localhost:3000/index  =>  https://www.baidu.com
    res.redirect('https://www.baidu.com');
});

5.res.cookie(name, value [, options]):设置 cookie

// 设置 cookie 。使用 res.cookie(name, value [, options])
// GET http://localhost:3000/setCookie
app.get('/setCookie', (req, res) => {
    res.cookie("name", 'zhangsan');
    res.send('设置cookie成功');
});

6.res.clearCookie(name [, options]):删除指定 cookie

//删除cookie
app.get('/deleteCookie',(req,res)=>{
    res.clearCookie("name");
    res.send('删除cookie成功');
});

7.res.sendFile(path [, options] [, fn]):传送指定路径的文件

//传送指定路径的文件
app.get('/file/:name', function (req, res, next) {
    var options = {
        root:__dirname,
        dotfiles: 'deny',
        headers: {
            'x-timestamp': Date.now(),
            'x-sent': true
        }
    }

    var fileName = req.params.name
    res.sendFile(fileName, options, function (err) {
        if (err) {
            next(err)
        } else {
            console.log('Sent:', fileName)
        }
    })
})

更多

三.静态资源托管

使用 Express 中内置的 express.static() 中间件来处理项目中的 html、js、css、img 等静态资源文件。

1.首先,我们需要选定你要作为静态资源托管的目录。这里使用的是 public 目录

在这里插入图片描述

2.调用 express.static() 中间件

const express = require('express');

const app = express();

//处理静态资源托管
app.use(express.static('./public'));//中间件必须要app.use调用


app.listen(3000, function () {
	console.log("服务启动成功");
});

3.访问

1.html http://localhost:3000/1.html

bg.jpg http://localhost:3000/bg.jpg

index.js http://localhost:3000/index.js

4.设置前缀

我们一般用法也是使用这种

const express = require('express');

const app = express();

//处理静态资源托管
//app.use(express.static('./public'));//中间件必须要app.use调用

//设置访问静态资源前缀
app.use('/static', express.static('./public'));

// 其实 app.use() 第一个参数没有写的时候,默认是 /
// app.use('/', express.static('./public'))
app.listen(3000, function () {
    console.log("服务启动成功");

});

这时,我们需要在路径前面加static

1.html http://localhost:3000/1.html

bg.jpg http://localhost:3000/bg.jpg

index.js http://localhost:3000/index.js

发布了17 篇原创文章 · 获赞 40 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/liuqiao0327/article/details/105129881