Express获得get和post请求参数

获得get请求参数

app.get('/index',function (req,res) {
    var params = req.query
})

获得post请求参数,post发送的参数是在请求体中的,Express没有提供获取表单post请求体的api,我们需要使用到第三方包

cnpm install body-parser

在项目中引入

var bodyParser = require('body-parser')

添加解析插件,它将解析所有传入请求的主体。

var express = require('express') var bodyParser = require('body-parser') var app = express() // 创建application/json 解析器 var jsonParser = bodyParser.json() // 创建 application/x-www-form-urlencoded 解析器 var urlencodedParser = bodyParser.urlencoded({ extended: false }) 
//把body解析器专门添加到需要它们的路由中 app.post('/login', urlencodedParser, function (req, res) { res.send('welcome, ' + req.body.username) }) app.post('/api/users', jsonParser, function (req, res) { // create user in req.body })

官网有更多相关介绍

猜你喜欢

转载自www.cnblogs.com/a-small-lyf/p/10766261.html