2

I got an error :

422 (Unprocessable Content)

when I tried to post a data in register form

I have this in my Register.vue

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

and in my 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));
    },
  }

Anyone know where I'm wrong ? Many thanks

1 Answer 1

3

Don't return twice if the request is good.

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

Also use async/await. I'd do

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

And in the 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));
    });
  },
};

Also you can put it in try/cache etc. It's up to you.

Check the docs, it well explained.

Sign up to request clarification or add additional context in comments.

3 Comments

Many thanks for your answer ! fetch is working but I still got error 422 . It's look like my data doesnt send to backend, maybe it's because of dispatch?
Well then it's not a FE issue. Check your logs for more info, what is happening. If the data is being processed on the BE part.
I see many thanks for your help !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.