美文网首页
node body-parser解析post请求数据

node body-parser解析post请求数据

作者: 唐卡豆子 | 来源:发表于2018-10-15 21:04 被阅读0次

body-parser是一个HTTP请求体解析中间件,使用这个模块可以解析JSON、Raw、文本、URL-encoded格式的请求体

安装

npm install body-parser -S

使用

在app.js文件中

// 引入
let bodyParser = require('body-parser')

// 解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended:true}))
// 解析 application/json 
// 判断请求体格式是不是json格式 如果是的话会调用JSON.parse方法把请求体字符串转成对象
app.use(bodyParser.json())

// 获取post请求传递过来的参数值
let user = req.body

前端发送请求:

methods:{
             loginIn(){
                this.$axios.post('/user/login', {'mobile':'18912341234', 'password':'123456'})
                    .then(result=>{
                        if(result.data.code == 0){
                            console.log('用户名或密码不正确')
                        }else if(result.data.code == 1){
                            console.log('登录成功')
                            this.$router.push(this.$route.query.redirect || '/')
                        }
                    })
            }
        }

后台数据:

let express = require("express");
let bodyParser = require("body-parser");
let app = express();

app.listen(8084); 
app.use(bodyParser.urlencoded({extened:false}));
app.use(bodyParser.json());

app.post("/user/login", (req, res)=>{
    let {mobile, password} = req.body;
    console.log(mobile, password);//  18928726497 123456
    ......
});


参考:https://blog.csdn.net/yanyang1116/article/details/54847560

相关文章

网友评论

      本文标题:node body-parser解析post请求数据

      本文链接:https://www.haomeiwen.com/subject/qwhaaftx.html