一般概念:我正在訪問兩個 API 端點。一個回應一般資訊,另一個回應特定資訊。
我已經呼叫了第一個端點并通過回應,我以第二個端點作為引數所需的格式回傳了一個物件。
問題:我不斷收到“轉換后的資料必須是字串、ArrayBuffer、緩沖區或流”
我想學習跨控制器使用功能,以免自己重復。
代碼:
這將回傳我需要在第二個 API 呼叫中使用的物件:
const axios = require("axios");
const getSpecials = async (req, res) => {
try {
const response = await axios.get(`${apiURL}/categories`);
let specials = [];
let skus = [];
response.data.forEach((element, index) => {
if (response.data[index].is_special == true) {
specials.push({
name: response.data[index].name,
product_skus: response.data[index].product_skus,
_id: response.data[index]._id,
});
skus.push(response.data[index].product_skus);
}
});
return { product_skus: skus.flat() };
} catch (error) {
console.log(error.message);
}
};
module.exports = {getSpecials}
如果我將第一個 API 呼叫的回傳作為引數發布,這將回傳產品詳細資訊:
const axios = require("axios");
const { getSpecials } = require("./categoriesControllers");
const specialProducts = async (req, res) => {
try {
const response = await axios.post(`${apiURL}/products`, getSpecials);
res.status(200).json(response.data);
} catch (error) {
console.log(error.message);
}
};
任何關于如何最好地做到這一點的建議都會很棒。我想學習讓后端完成所有繁重的作業,并且我想盡可能干凈地將資料提供給前端。
uj5u.com熱心網友回復:
如果我理解正確,你只需要改變
const response = await axios.post(`${apiURL}/products`, getSpecials);
對此
const response = await axios.post(`${apiURL}/products`, await getSpecials());
因為現在您將函式宣告傳遞給 axios post 函式的第二個引數,而不是 getSpecials 的回傳值
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/424028.html
標籤:javascript 节点.js axios 后端
