【问题标题】:Got error 422 with vuex (dispatch) in vuejsvuejs 中的 vuex (dispatch) 出现错误 422
【发布时间】:2022-01-03 16:51:26
【问题描述】:

我遇到了一个错误:

422 (Unprocessable Content)

当我尝试在注册表中发布数据时

我的 Register.vue 中有这个

  methods: {
    register() {
      this.$store.dispatch('register', {
        firstname: this.firstname,
        lastname: this.lastname,
        email: this.email,
        password: this.password,
      });
    },
  },
};

在我的 vuex 中

  actions: {
    register(credentials) {
      const requestOptions = {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        dataType: 'json',
        body: JSON.stringify(credentials),
      };
      console.log(credentials);
      return fetch('http://localhost/api/users', requestOptions)
        .then((response) => {
          return response.json;
        })
        .catch((err) => console.log(err.message));
    },
  }

有人知道我错在哪里吗? 非常感谢

【问题讨论】:

    标签: vue.js fetch vuex


    【解决方案1】:

    请求好的不要返回两次。

      actions: {
        register(credentials) {
          const requestOptions = {
            method: 'POST',
            headers: { 'content-type': 'application/json' },
            dataType: 'json', // not needed 
            body: JSON.stringify(credentials),
          };
          console.log(credentials);
          return fetch('http://localhost/api/users', requestOptions) // first time
            .then((response) => {
              return response.json; // second time
            })
            .catch((err) => console.log(err.message));
        },
      }
    

    也使用异步/等待。我愿意

      actions: {
        async register(credentials) {
        
          const requestOptions = {
            method: 'POST',
            headers: { 'content-type': 'application/json' },
            dataType: 'json',
            body: JSON.stringify(credentials),
          };
        
          const res = await fetch('http://localhost/api/users', requestOptions);
        }
    
        return res.json();
      }
    

    而在Register.vue

      methods: {
        register() {
          this.$store.dispatch('register', {
            firstname: this.firstname,
            lastname: this.lastname,
            email: this.email,
            password: this.password,
          }).then(data => {
            console.log(data)
          }).catch((err) => console.log(err.message));
        });
      },
    };
    

    你也可以把它放在 try/cache 等中。这取决于你。

    查看docs,解释得很好。

    【讨论】:

    • 非常感谢您的回答! fetch 正在工作,但我仍然收到错误 422 。看起来我的数据没有发送到后端,可能是因为调度?
    • 那么这不是 FE 问题。检查您的日志以获取更多信息,发生了什么。如果数据正在 BE 部分处理。
    • 非常感谢您的帮助!!
    猜你喜欢
    • 2021-07-21
    • 2016-06-19
    • 2020-07-21
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2022-01-04
    • 2020-10-26
    • 2020-11-03
    相关资源
    最近更新 更多