Reactjs 使用post方法提交表单时,如何模拟错误消息?
我刚刚加入的项目不使用来自后端的API,但必须通过Axios mock适配器自行创建模拟数据。我正在制作一个表格来更改密码,如果输入正确,提交它将成功显示,如果输入不正确,将显示一个错误(例如输入不为空,密码不匹配…),如何做到这一点Reactjs 使用post方法提交表单时,如何模拟错误消息?,reactjs,axios-mock-adapter,Reactjs,Axios Mock Adapter,我刚刚加入的项目不使用来自后端的API,但必须通过Axios mock适配器自行创建模拟数据。我正在制作一个表格来更改密码,如果输入正确,提交它将成功显示,如果输入不正确,将显示一个错误(例如输入不为空,密码不匹配…),如何做到这一点 .onPost("/user/changepassword"), { // How can I pass the values of the inputs }) .reply(() => { //
.onPost("/user/changepassword"), {
// How can I pass the values of the inputs
})
.reply(() => {
// How can I check the value of the inputs: empty, password input does not match...
if (conditions are ok) {
return [200, MOCK_RESPONSE.SUCCESS];
} else {
return [200, MOCK_RESPONSE.ERROR];
}
});
您可以尝试以下代码:
var mock = new AxiosMockAdapter(axios);
mock.onPost(/\/api\/*/).reply(config => {
var params = Object.fromEntries(new URLSearchParams(config.data));
if (params.name === 'tommy') {
return [200, {success:true}];
} else {
return [200, {success:false}];
}
})
axios.post('/api', (new URLSearchParams({name: 'tommy'})).toString()).then((res) => {
console.log(res.data)
})