I've been working on a VUE application and I'm currently exploring how to handle post responses with Axios. Initially, I used vue-router for fetching data but decided to give Axios a try.
Axios code:
methods: {
sendForm () {
console.log("submitHandler called - success!");
const payload = {
first_name: this.event.firstName,
last_name: this.event.lastName,
email: this.event.email,
password: this.event.password,
name: this.event.agencyName,
abbreviation: this.event.abbreviation,
type: this.event.agencyType,
address: this.event.agencyAddress,
city: this.event.agencyCity,
state: this.event.state,
zipcode: this.event.zipcode,
phone: this.event.phone,
}
axios.post(process.env.VUE_APP_API_URL+"/agency/add",payload)
.then(function (response) {
console.log('Response', response)
//reformat returned expiration date for displaying on webpage
console.log("Expiry date:", response.data.data.agency.expiry);
let expd = dayjs(response.data.data.agency.expiry).format("dddd, MMMM D YYYY");
//Write retunred values to storeage
store.user = {
id: response.data.data.user.id,
first_name: response.data.data.user.first_name,
last_name: response.data.data.user.last_name,
email: response.data.data.user.email,
agency_name: response.data.data.agency.name,
expiry_date: expd,
}
router.push("/SignUpConfirm");
})
.catch(function (error) {
console.log('Error', error.message);
Swal.fire({
icon: 'error',
title: 'Oops...',
text: error.message,
})
})
}
}
The issue/question I have is that I need to use "response.data.data.foo" to access the desired response, whereas with the built-in view router, I only needed to use "data.foo"
Vue-router option:
methods: {
submitHandler() {
console.log("submitHandler called - success!");
const payload = {
first_name: this.firstName,
last_name: this.lastName,
email: this.email,
password: this.password,
agency_name: this.agencyName,
abbreviation: this.abbreviation,
agency_type: this.agencyType,
agency_address: this.agencyAddress,
agency_city: this.agencyCity,
state: this.state,
zipcode: this.zipcode,
phone: this.phone,
}
const requestOptions = {
method: "POST",
body: JSON.stringify(payload),
}
fetch(process.env.VUE_APP_API_URL+"/agency/add", requestOptions)
.then((response) => response.json())
.then((response) => {
if (response.error) {
console.log("Error:", response.message);
Swal.fire({
icon: 'error',
title: 'Oops...',
text: response.message,
})
} else {
//reformat returned expiration date for displaying on webpage
console.log("Expiry date:", response.data.agency.expiry);
let expd = dayjs(response.data.agency.expiry).format("dddd, MMMM D YYYY");
//Write retunred values to storeage
store.user = {
id: response.data.user.id,
first_name: response.data.user.first_name,
last_name: response.data.user.last_name,
email: response.data.user.email,
agency_name: response.data.agency.name,
expiry_date: expd,
}
router.push("/SignUpConfirm");
}
})
}
}