記使用axios請求easy-mock數(shù)據(jù)時碰到的問題
第一次使用axios帶參數(shù)來請求easy-mock模擬的數(shù)據(jù),碰到一個問題:返回值不能正確返回。
查閱相關(guān)資料后,發(fā)現(xiàn)是content??Type的問題
axios默認(rèn)使用Content-Type: application/json; charset=utf-8方式來發(fā)送數(shù)據(jù),easy-mock的相應(yīng)方式也是Content-Type: application/json; charset=utf-8,但是使用如下easy-mock的響應(yīng)數(shù)據(jù)格式,不能正確返回數(shù)據(jù)
axios
axios.post('https://easy-mock.com/mock/5a28f3c05f502a311f5cdb04/getNewsList/load', {
'name': this.usernameModel
}).then(data => {
console.log(data);
}).catch(error => {
console.log(error);
});
easy-mock
{
success: true,
data: {
default: '用戶名錯誤',
_req: function({ _req }) {
return _req
},
name: function({ _req }) {
if (_req.query.name === 'admin') {
return _req.body.name
} else {
return this.default
}
}
}
}
后來修改axios的數(shù)據(jù)請求格式為application/x-www-form-urlencoded,easy-mock修改_req.query.name成_req.body.name后,可以正確接收到返回值。
貼上正確完整的?代碼:
axios部分
import qs from 'qs'; //使用qs庫處理axios請求的數(shù)據(jù)格式為application/x-www-form-urlencoded
axios.post('https://easy-mock.com/mock/5a28f3c05f502a311f5cdb04/getNewsList/load', qs.stringify({
'name': this.usernameModel
})).then(data => {
console.log(data);
}).catch(error => {
console.log(error);
});
easy-mock部分
{
success: true,
data: {
default: '用戶名錯誤',
_req: function({
_req
}) {
return _req
},
name: function({
_req
}) {
if (_req.body.name === 'admin') {
return _req.body.name
} else {
return this.default
}
}
}
}