简体   繁体   English

运行 axios 获取请求时收到 400 错误代码?

[英]Getting 400 error code when I run axios get request?

I write some code to getting info我写了一些代码来获取信息

const stock = await Stock.find({
    exchange: exchange
});
// Here stock array length is 5300

stock.forEach(async (stockEl) => {
    const EOD_API = process.env.EOD_HISTORICAL_API
    const {data} = await axios.get(`https://eodhistoricaldata.com/api/fundamentals/${stockEl.code}?api_token=${EOD_API}&filter=General::Industry`);
    console.log(data);
});

Here I place get request for every stock array element by forEach function.在这里,我通过forEach function 对每个股票数组元素发出请求。 Then it give me error like image- Click to see images然后它给我像图像一样的错误-点击查看图像

But When I place it outside of forEach function like this-但是当我像这样将它放在 forEach function 之外时-

const EOD_API = process.env.EOD_HISTORICAL_API
const {data} = await axios.get(`https://eodhistoricaldata.com/api/fundamentals/${stockEl.code}?api_token=${EOD_API}&filter=General::Industry`);
console.log(data);

Then it gives no error.然后它没有错误。 For Remembering Stock has 5300 element, that means axios run 5300 times.因为记忆股票有 5300 个元素,这意味着 axios 运行 5300 次。

Any solution or idea?任何解决方案或想法?

Doing await in forEach doesn't hold the process since forEach is not promise-aware.在 forEach 中执行 await 不会保留该过程,因为 forEach 不是承诺感知的。 Try this instead:试试这个:

(async () => {
    for (let index = 0; index < stock.length; index++) {
        const EOD_API = process.env.EOD_HISTORICAL_API
        const {data} = await axios.get(`https://eodhistoricaldata.com/api/fundamentals/${stock[i].code}?api_token=${EOD_API}&filter=General::Industry`);
        console.log(data);
    }
})();

More information .更多信息

You need to make a few changes:您需要进行一些更改:

  • Replace forEach with for because forEach is not promise aware将 forEach 替换为 for 因为 forEach 不支持 promise

  • Use try, catch => catch any errors使用 try, catch => 捕获任何错误

  • Use Promise.allSettled => it allows you to run all promisses together without waiting each other which in return will enhance your app performance.使用 Promise.allSettled => 它允许您一起运行所有承诺,而无需相互等待,这反过来会提高您的应用程序性能。 It returns an array with status ("fulfilled", "rejected")它返回一个状态为 ("fulfilled", "rejected") 的数组

    const fetchSingleStockElement = async (stockEl) => { try { const EOD_API = process.env.EOD_HISTORICAL_API, { data } = await axios( `https://eodhistoricaldata.com/api/fundamentals/${stockEl.code}?api_token=${EOD_API}&filter=General::Industry` ); return data; } catch (err) { throw new Error(err); } }; const fetchAllStockData = async () => { let promisesArray = []; try { //fetch stock array const { data } = await Stock.find({ exchange: exchange }); //fetch single stock for (let i = 0; i < data.length; i++) { promisesArray.push(fetchSingleStockElement(data[i].id)); } const results = await Promise.allSettled(promisesArray); console.log('results', results); } catch (err) { console.log('results error', err); }

    }; };

Here is a working example with fake API of 4466 entries:这是一个带有 4466 个条目的假 API 的工作示例:

const fetchSingleAirline = async (airlineId) => {
        try {
            const { data } = await axios(`https://api.instantwebtools.net/v1/airlines/${airlineId}`);
            return data;
        } catch (err) {
            throw new Error(err);
        }
    };

const fetchAllAirlineData = async () => {
    let promisesArray = [];
    try {
        const { data } = await axios('https://api.instantwebtools.net/v1/airlines');
        for (let i = 0; i < data.length; i++) {
            promisesArray.push(fetchSingleAirline(data[i].id));
        }

        const results = await Promise.allSettled(promisesArray);
        console.log('results', results);
    } catch (err) {
        console.log('results error', err);
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM