node第三方模块body-parser的urlencoded方法的extended参数说明

node第三方模块body-parser的urlencoded方法的extended参数说明

const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/add', (res, req) => {
    res.send(res.body);
});
app.listen(2000);

服务器端

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
app.use(express.static(path.join(__dirname, 'public')))
app.use(bodyParser.urlencoded({
    extended: false
}));
app.post('/test', (req, res) => {
    console.log(req.body.name);
    //req.body.name用来解析客户端的post请求参数得到传过来得name属性的值
    res.send(req.body.name)
})
app.listen(2000)
console.log('服务器启动成功');

客户端:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>
        fetch('http://localhost:2000/test', {
            method: 'post',
            body: 'name=zs&age=18',
            headers: {
            //(1)application/x-www-form-urlencoded
//最常见的 POST 提交数据的方式。浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。
//首先,Content-Type 被指定为 application/x-www-form-urlencoded;其次,提交的数据按照 key1=val1&key2=val2 的方式进行编码,key 和 val 都进行了 URL 转码。大部分服务端语言都对这种方式有很好的支持。
                'Content-Type': 'application/x-www-form-urlencoded',
            }
        }).then(function (data) {
            return data.text();
        }).then(function (data) {
            console.log(data);
        });
    </script>

</body>

</html>
  1. extended: false:表示使用系统模块querystring来处理,也是官方推荐的
  2. extended: true:表示使用第三方模块qs来处理
  3. 从功能性来讲,qs比querystring要更强大,所以这里可以根据项目的实际需求来考虑
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值