node.js - vue中 post數據遇到問題
問題描述
我在vue-cli中的dev-server.js中寫了post的接口
app.use(bodyParser.urlencoded({ extended: true }));var apiRouters = express.Router();// 寫幾個接口apiRouters.post(’/login’, function (req, res) { console.log(req.body);})app.use(’/api’, apiRouters);
然后在vue組件中用axios請求
methods: { submitForm(formName) {this.$refs[formName].validate((valid) => { if (valid) { alert(’submit!’); let loginParams = { username: this.ruleForm.account, password: this.ruleForm.checkPass }; this.axios.post(’/api/login’,loginParams).then(response => {console.log(response); }) } else { console.log(’error submit!!’); return false; }}); }, resetForm(formName) { console.log(’reset’); this.$refs[formName].resetFields(); }}
當我請求時后端打出的req.body一直是一個空對象,但是我看了下瀏覽器明明是有post數據過去的
我想問問這是為啥==
問題解答
回答1:問題應該出在你的dev-server.js里,你缺了對requestBody的正確處理,改成這樣:
app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));var apiRouters = express.Router();// 寫幾個接口apiRouters.post(’/login’, function (req, res) { console.log(req.body);})app.use(’/api’, apiRouters);
再試一次
回答2:你可以試試打印req或者打印一個數字1看看請求有沒有進去。還可以res.send()一個值看能不能拿到。
相關文章:
1. javascript - win7 npm安裝gulp失敗,已是管理員打開,也設置了文件權限2. jquery - jquey tabs ajax load html 沖突問題?3. css3 - css垂直水平居中?4. 同一個html頁面用多個id有什么影響?5. javascript - 小程序中遇到js執行時序問題6. Safari的html5 localStorage錯誤:“ QUOTA_EXCEEDED_ERR:DOM異常22:試圖向存儲中添加超出配額的內容。”7. 在微信瀏覽器中使用iframe,android會出現空白,ios會跳轉,怎么阻止這些?8. javascript - 表單ajax提交后跳轉,手機按返回又進入這個表單頁了!!9. css - 使用rem布局的問題10. 從Runtime.getRuntime()。exec()啟動wkhtmltopdf:永不終止?
