我正在尝试正确构造后端,并且想知道是否可以在同一操作中向我的API发出多个POST请求(到不同的端点和具有不同的数据)?如果是这样,我是否需要将第二个.post
包装在.then()
中?
export function signup({ email, password }) {
return function(dispatch) {
console.log("signup function ran");
axios
.post("https://MYAPI.com/signup", { email, password }) //first POST
.then(response =>
dispatch({
type: LOG_IN,
payload: response.data.token
})
)
.post("https://MYAPI.com/user", { data1, data2 }) // second POST
.then(navigate("mainFlow"))
.catch(error => {
console.log(error);
});
};
}
答案 0 :(得分:1)
也许您可以使用如下的async await语法进行尝试:
export function signup({ email, password }) {
return async function(dispatch) {
console.log("signup function ran");
try {
const response1 = await axios.post("https://MYAPI.com/signup", {
email,
password
});
dispatch({
type: LOG_IN,
payload: response1.data.token
});
const response2 = await axios.post("https://MYAPI.com/user", {
data1,
data2
});
navigate("mainFlow");
} catch (error) {
console.log(error);
}
};
}