gpt4 book ai didi

javascript - (多个)axios Post请求/参数问题

转载 作者:行者123 更新时间:2023-12-01 01:39:09 25 4
gpt4 key购买 nike

这是一个由多部分组成的问题(巧合的是我在 Stack 上遇到的第一个问题!)。作为前言,我正在构建一个带有 Rails 后端和 Vue.js 前端的网站。

我的问题是 Axios POST 请求。我正在尝试通过单击提交按钮发送两个 POST 请求。我有一个“Trips” Controller 和一个“User_Trips” Controller - 后者的功能是连接到我的数据库中的其他表。为了显示新创建的行程,还需要创建新的 user_trip。

我的旅行发布得很好,当我在 Postico 中查找时会显示出来,但我的 user_trip 没有成功发布,我认为这是因为我正在努力确定如何通过最近的通过创建旅行的 id 作为创建 user_trip 所需的参数。这是我正在处理的 Vue.js 代码的一部分:

<script>
import axios from "axios";
export default {
data: function() {
return {
trips: [],
errors: [],
name: "",
country: "",
state: "",
city: "",
postal_code: "",
start_date: "",
end_date: "",
image: "",
trip: this.trip
};
},
mounted: function() {
// axios.get("http://localhost:3000/api/trips").then(
// function(response) {
// console.log(response);
// this.trips = response.data.trips;
// }.bind(this)
// );
},
methods: {
submit: function() {
var params = {
name: this.name,
country: this.country,
state: this.state,
city: this.city,
postal_code: this.postal_code,
start_date: this.start_date,
end_date: this.end_date,
image: this.image
};
axios
.post("http://localhost:3000/api/trips", params)
.then(response => {
axios.get("http://localhost:3000/api/trips").then(
function(response) {
console.log(response);
this.trips = response.data.trips;
}.bind(this)
);
})
.catch(error => {
this.errors = error.response.data.errors;
});
var paramsTwo = {
trip_id: this.trip.id
};
axios
.post("http://localhost:3000/api/usertrips", paramsTwo)
.then(response => {
this.$router.go("/home");
})
.catch(error => {
this.errors = error.response.data.errors;
});
}
}
};
</script>

这是我在控制台日志中收到的错误消息:未捕获的类型错误:无法读取未定义的属性“id”,我认为这是因为我没有从数组中选择正确的行程...但是当我查看日志中的 GET 请求时,新创建的行程不会显示 - 它只在我的数据库中可见。任何有用的建议将不胜感激!- 谢谢

最佳答案

想通了!非常感谢有用的评论者和回答者。

<script>
import axios from "axios";
export default {
data: function() {
return {
trips: [],
errors: [],
name: "",
country: "",
state: "",
city: "",
postal_code: "",
start_date: "",
end_date: "",
image: "",
};
},
mounted: function() {
},
methods: {
submit: function() {
var params = {
name: this.name,
country: this.country,
state: this.state,
city: this.city,
postal_code: this.postal_code,
start_date: this.start_date,
end_date: this.end_date,
image: this.image
};
axios
.post("http://localhost:3000/api/trips", params)
.then(response => {
console.log(response);
this.trip = response.data;
var paramsTwo = {
trip_id: this.trip.id
};
axios
.post("http://localhost:3000/api/usertrips", paramsTwo)
.then(response => {
this.$router.go("/home");
})
.catch(error => {
this.errors = error.response.data.errors;
});
}
);
}
}
};
</script>

关于javascript - (多个)axios Post请求/参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52571896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com