javascript - 当我的数据位于 .then 承诺中时,如何在下一个 js 中的 API 路由中发送我的响应
问题描述
我正在使用带有 axios 的下一个 js,并且我在 .then 中有一个 .then 承诺。我想用我抓取的数据来响应 api 请求,但是如果我将 res 放在 .then 中,则无法访问,但我不知道如何从 .then 中获取数据。通常使用异步等待我返回值并为函数创建一个变量,但这似乎不适用于.then。
这是我的代码
let data;
axios
.post(
"https://accounts.spotify.com/api/token",
serialize({
grant_type: "client_credentials",
}),
{
headers: {
Authorization: "Basic " + auth,
},
}
)
.then((res) => {
axios
.get(
`https://api.spotify.com/v1/search?q=${name}&type=episode&market=US`,
{
headers: {
Authorization: `Bearer ${res.data.access_token}`,
"Content-Type": "application/json",
},
}
)
.then(function (response) {
// handle success
console.log(response.data.episodes);
data = response.data.episodes;
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
})
.catch((err) => {
console.log(err);
});
res.status(200).json({ data: data });
任何帮助将不胜感激谢谢
解决方案
以下修复了它
const data = axios
.post(
"https://accounts.spotify.com/api/token",
serialize({
grant_type: "client_credentials",
}),
{
headers: {
Authorization: "Basic " + auth,
},
}
)
.then((res) => {
const test = axios
.get(
`https://api.spotify.com/v1/search?q=${name}&type=episode&market=US`,
{
headers: {
Authorization: `Bearer ${res.data.access_token}`,
"Content-Type": "application/json",
},
}
)
.then(function (response) {
// handle success
// console.log(response.data.episodes);
return response.data.episodes;
})
.catch(function (error) {
// handle error
console.log(error);
});
return test;
})
.catch((err) => {
console.log(err);
});
const boy = async () => {
console.log("data", await data);
res.status(200).json({ data: await data });
};
boy();
推荐阅读
- android - Android 构建失败,无法解决:com.squareup.retrofit2:convertor-gson:2.7.1
- google-apps-script - 谷歌表格应用脚本查找这一天的本周日期,以及同一天的下一周日期
- python - APNS,当程序在 Mac 上运行时,如何修复树莓派上的“无法获取本地颁发者证书”错误?
- copy - 复制一个文件夹并为每个月创建一个新文件夹
- python - 将 int(number) 转换为列表,int 数在 python 中可能为负数
- c# - 我将我的 C# 程序添加到 Windows 注册表中如何获取我在代码中右键单击的文件?
- ravendb - RavenDB RQL 中的 LastIndexOf?
- node.js - 正方体的问题
- presto - 在超集中,如何排除我的字段包含 {} 值的结果?
- java - 如何每 5 分钟在上午 9:30 到下午 4:00 之间在 Spring Boot 中运行作业?