express获取表单get和post请求的 数据

GET请求的参数在URL中,在原生Node中,需要使用url模块来识别参数字符串。在Express中,不需要使用url模块了。可以直接使用req.方法来直接获取。

app.get('/getFile', function (req, res) {

  let comm = req.query
     console.log(comm) //{ a: '100', b: '200' }
     console.log(req.host)
     console.log(req.url)
     console.log(req.method)


})

POST 请求: 在Express 中 没有内置获取表单POST请求体的API,这里我们需要使用一个第三方的包 :body-parser
第一步:

npm install body-parser
1
第二步:使用
2.1 导包:

var bodyParser = require('body-parser');
1
配置body-parser,只要加入这个配置则在req的请求对象上会多出来一个属性:body
也就是说可以直接通过req.body来获取表单post的请求体的数据了


//处理POST请求的
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())

app.post('/post', function (req, res) {
//通过req.body来获取POST的提交的请求体数据

console.log(req.body)


})
————————————————
版权声明:本文为CSDN博主「邪小新」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_42074075/java/article/details/89298033

猜你喜欢

转载自www.cnblogs.com/fsg6/p/13191859.html