Express 中 获取 get/post 传值

 

 

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


● POST 请求在 express 中不能直接获得,可以使用 body-parser 模块。使用后,将可以用
req.body 得到参数。但是如果表单中含有文件上传,那么还是需要使用 formidable 模块。


1.安装
npm install body-parser


2.使用 req.body 获取 post 过来的参数


var express = require('express');
var bodyParser = require('body-parser');
var app = express();


// 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))
})

 

 

posted @ 2018-12-08 18:11  aocn  阅读(953)  评论(0)    收藏  举报