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>
- extended: false:表示使用系统模块querystring来处理,也是官方推荐的
- extended: true:表示使用第三方模块qs来处理
- 从功能性来讲,qs比querystring要更强大,所以这里可以根据项目的实际需求来考虑