文章目录
- get
- post ※
安装
配置
使用示例 - get
get请求就很容易了,我们使用原生的API就可以了
在express中,req有一个 query属性
直接使用就拿到了
req.query
1.
例如:
app.get(’/example’, function (req, res) {
var data= req.query
data.dateTime = ‘2800-11-5 10:58:51’
data.unshift(comment)
// redirect 重定向到 /
res.redirect(’/’)
})
- post ※
在express中没有获取 表单post请求 的API ,我们要用第三方包来获取
body-parser 中间件
安装
npm install --save body-parser
1.
配置
var bodyParser = require(‘body-parser’)
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json(www.meimeitu8.com))
1.
2.
3.
使用示例
// 引包
var express = require(‘express’)
var bodyParser = require(‘body-parser’)
var app = express()
// 只要加上这两句配置,则在 post请求对象上会多出一个属性:body
// 也就是可以用 req.body 来获取发送过来的数据
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader(‘Content-Type’, ‘text/plain’)
res.write(‘you posted:\n’)
res.end(JSON.stringify(req.body, null, 2))
})
本文详细介绍了在ExpressJS中如何处理GET和POST请求。对于GET请求,可以通过req.query直接访问查询参数;而对于POST请求,由于Express内建不支持,需要使用body-parser中间件来解析请求体。通过安装并配置body-parser,可以获取req.body中的数据。示例代码展示了如何设置和使用这些中间件。

1525

被折叠的 条评论
为什么被折叠?



