body-parser是一個(gè)HTTP請(qǐng)求體解析中間件锰瘸,使用這個(gè)模塊可以解析JSON粹淋、Raw监透、文本蛋辈、URL-encoded格式的請(qǐng)求體
安裝
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
// 判斷請(qǐng)求體格式是不是json格式 如果是的話會(huì)調(diào)用JSON.parse方法把請(qǐng)求體字符串轉(zhuǎn)成對(duì)象
app.use(bodyParser.json())
// 獲取post請(qǐng)求傳遞過(guò)來(lái)的參數(shù)值
let user = req.body
前端發(fā)送請(qǐng)求:
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 || '/')
}
})
}
}
后臺(tái)數(shù)據(jù):
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