我正在尝试使用 axios 将多个对象从数组发布到 API,我还尝试将发布请求限制为每 10 秒 1 个。我有以下代码,但它没有给我任何东西,没有响应,错误,什么也没有。我做错了什么?
const axios = require("axios");
const { auth, baseUrl } = require("./connect");
const fs = require("fs");
// POST sample data
function postSales() {
auth.then(result => {
let token = result.access_token;
const data = fs.readFileSync("./temp/converted.json", "utf-8");
setTimeout(() => {
data.forEach(sale => {
axios
.post(
`${baseUrl}/sale.json`,
{ sale },
{
headers: {
Authorization: `Bearer ${token}`,
scope: `employee:all`
}
}
)
.then(res => console.log(res))
.catch(err => console.error(err));
});
}, 10000);
});
}
postSales();
最佳答案
fs.readFileSync
返回数据的字符串化版本。您需要JSON.parse
它。
const data = JSON.parse(fs.readFileSync("./temp/converted.json", "utf-8");)
使用setTimeout
或setInterval
将操作发送到事件队列并使等待间隔变得非常困难。使用 for
循环和使用 async
/await
语法更容易编写和推理。 JavaScript 中不存在 sleep
函数,但您自己创建一个函数很容易。
const sleep = ms => new Promise((resolve) => setTimeout(resolve, ms))
auth.then(async result => {
let token = result.access_token;
const data = JSON.parse(fs.readFileSync("./temp/converted.json", "utf-8");)
for (let sale of data) {
try {
const res = await axios.post() // didn't add params, for brevity
console.log(res)
await sleep(10_000) // 10 seconds
} catch (e) {
console.error(e)
}
}
})
关于javascript - 有人可以就我的 Axios Post 请求提供建议吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60763935/