Estoy creando una pequeña aplicación node-fetch que envía nombres de usuario a una API. Mi código funciona, pero lo que quiero lograr es enviar tres objetos con una sola llamada, pero no estoy seguro de cómo hacerlo. Intenté agregar tres objetos, separados con una coma, pero eso no funcionó, envía solo el primer objeto, ¿cómo puedo lograr eso? Aquí está mi código:
import fetch from 'node-fetch'; const baseUrl = "https://test"; const apiToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVsdfsCJ9.eyJodHRwczovL2d0bWh1Yi5jb20vYXBwX21ldGFkYXRhL2FjY291bnRJZCI6IjYxNDQ0YTEwZjdmZmUxMDAwMsdfsfWY3NWI2NiIsImlhdCI6MTYzMTg2NTM2MSwic3ViIjoiZ29vZ2xlLW9hdXRoMnwxMTUwNjc3Nzc1NzMzMsdfTQxMDk5sdfMjgifQ.0zZZS1ixt1srNU-XcEcUqoaJep0H64-YRInCCbUi6_8"; const accountId = "61444a1ad2r0f7213fsdfsffe10001f75b66"; const options = { method: "POST", headers: { Authorization: `Bearer ${apiToken}`, "gtmhub-accountid": accountId, "Content-type": "application/json; charset=UTF-8", Accept: "application/json, text/plain, */*", }, body: JSON.stringify( { email: "behn_jones@okrs.tech", firstName: "Behn", lastName: "Johnes", userName: "test", }, { email: "amy_wrent@okrs.tech", firstName: "Amy", lastName: "Wrent", userName: "test", }, { email: "jake_nordon@okrs.tech", firstName: "Jake", lastName: "Nordon", userName: "test", }, ), }; const createUser = (url, settings) => { return fetch(`${url}/users`, settings) .then((response) => response.text()) .then((data) => console.log(data)) .catch((error) => { console.log(error.message); }); }; createUser(baseUrl, options);No tiene más remedio que hacer tres solicitudes separadas. Sin embargo, puede usar Promise.all() para hacer que su código sea un poco menos repetitivo y para aumentar el rendimiento al ejecutar las solicitudes en paralelo:
const requestBodies = [ { email: "asdfjkl@gmail.com", firstName: "Joe", lastName: "Citizen", username: "joe.citizen1" }, // ... ]; return Promise.all(requestBodies.map((body) => fetch(`${url}/users`, { method: "POST", headers: { Authorization: `Bearer ${apiToken}`, "gtmhub-accountid": accountId, "Content-type": "application/json; charset=UTF-8", Accept: "application/json, text/plain, */*", }, body }) .then((res) => res.text()) .then(console.log) .catch((err) => console.log(error.message)) ); // This returns a promise that resolves to an array of all the results.También un poco sin relación, pero creo que podría haber filtrado su token de API.
Editar: también asegúrese de respetar las reglas de la API y no enviar spam a una gran cantidad de solicitudes, o puede tener una tasa limitada.