I am beginner web developer.
I make my first project in due and laravel 8.
My API return me error: {"message":"The given data was invalid.","errors":{"email":["Taki email ju\u017c wyst\u0119puje."], "login":["Taki login ju\u017c wyst\u0119puje."]}}
I have this code:
axios.post(this.$apiAdress '/api/administrators?token=' localStorage.getItem("api_token"),
self.record
)
.then(function (response) {
if (response.data.status == 'success') {
Swal.fire(
'Sukces',
'Rekord dodany poprawnie!@',
'success'
)
} else {
Swal.fire(
'Błąd',
response,
'error'
)
}
this.$router.replace({path: '/administrators/create'});
}).catch(function (error) {
if (error.response.data.message == 'The given data was invalid.') {
Swal.fire(
'Błąd',
'Proszę wypełnić wszystkie pola oznaczone gwiazdką!',
'error'
)
window.scrollTo({top: 0});
}
In linę: error.response.data.message I have this errors.
I need print errors in Swal:
Swal.fire(
'Błąd',
'.... Here errors ....',
'error'
)
For example:
Swal.fire(
'Błąd',
'Taki email ju\u017c wyst\u0119puje. <br/> Taki login ju\u017c wyst\u0119puje.',
'error'
)
How can I make it?
Please help me
CodePudding user response:
You can just iterate over the errors
object:
if (error.response.data.message == 'The given data was invalid.') {
let error_details = ""
for (let key in error.response.data.errors) {
error_details = `${error.response.data.errors[key]}<br/>`
}
Swal.fire(
'Błąd',
error_details,
'error'
)
// ...
}
CodePudding user response:
This should work in this specific example:
Swal.fire(
'Błąd',
error.response.data.email "<br />" error.response.data.login,
'error'
)
CodePudding user response:
You're printing an entire object which results in this:
"[object Object]"
You need to get the property FROM the object.
response.error.email
// Taki email ju\u017c wyst\u0119puje. <br/> Taki login ju\u017c wyst\u0119puje.
Or to print the object as string:
JSON.stringify(response);
You can also get the specific errors.
var errors = JSON.parse('{"message":"' response.message '","errors":' JSON.stringify(response.errors) '}');
// Object { ... }