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
CodePudding user response:
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.