简体   繁体   English

使用 post 方法提交表单时如何模拟错误消息?

[英]How can I mock error message when submit form with post method?

The project I just joined does not use an API from the backend but must create mock data by itself through the Axios-mock-adapter.我刚刚加入的项目没有使用后端的API,而是必须通过Axios-mock-adapter自行创建模拟数据。 I am making a form to change the password, if the inputs entered are correct, submit it will display successfully, if the inputs are not correct, an error will be displayed (eg input is not blank, the password is not matched...) How to do that?我正在做一个修改密码的表格,如果输入正确,提交会显示成功,如果输入不正确,会显示错误(例如输入不为空,密码不匹配... ) 怎么做?

.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];
      }
    });

You can try this code:你可以试试这个代码:

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)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM