Fetch inside of map - javascript

I am trying to fetch data from a Socrata API and then post it to my own database. When I run the function in node, I get the error "ReferenceError: fetch is not defined"
I am totally lost, and am wondering how to pull this off. I have been googling for the past four hours, and can't find anything.
My code:
const apiURL = "https://ftbserver.herokuapp.com/npos"
const soda = require('soda-js');
var consumer = new soda.Consumer('data.colorado.gov');
let stuff
consumer.query()
.withDataset('p3jp-z4tq')
.limit(2)
.where({ principalcity: 'Denver' })
// .order('namelast')
.getRows()
.on('success', function (rows) {
rows.map((nposNew) => {
let data = {
fein: nposNew.fein,
name: nposNew.name,
revenuetotal: nposNew.revenuetotal,
expensestotal: nposNew.expensestotal
}
fetch(apiURL, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(data)
})
.then(response => response.json())
.then(response => {
showSuccess(response.message)
setTimeout(() => (removeMsg()), 4000);
})
.catch(console.error);
})
})
.on('error', function (error) { console.error(error); });
// console.log(stuff);
// console.log(npost);

Related

react-native api call got stuck

I am doing a simple API call in a function. The API Response is fine in Postman it 280 ms to 340 ms. but in my Application it taks 5 to 10 mins. Here is my function.
const getSuggestions = async query => {
const filterToken = query.toLowerCase();
if (query.length < 3) {
setLoading(false);
return;
}
setLoading(true);
var myHeaders = new Headers();
myHeaders.append(
'Authorization',
'Basic xyzxyzxyzxyzxyzyzyzyzy',
);
myHeaders.append('Content-Type', 'application/json');
var raw = JSON.stringify({
query: filterToken,
language: 'en',
});
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
};
fetch(
'https://api.worldota.net/api/b2b/v3/search/multicomplete/',
requestOptions,
)
.then(response => response.json())
.then(response => {
const sections = [];
Object.keys(response.data).map((item, i) => {
sections.push({
title: item,
data: response.data[item],
});
});
setSuggestionsList(sections);
setLoading(false);
})
.catch(err => {
console.log(err);
setLoading(false);
});
};
when ever my search params are changed then i call this function. whats is the problem with my function. it was working fine last day. :(

getting error while trying to upload image to node server

Using this tutorial I want to upload images to my database, So I have this in server side:
router.post('/upload', upload.single('upload'), async (req, res) => {
try {
const incident = await Incident.findById(req.body.id)
incident.image = req.file.buffer
incident.save()
res.send()
} catch (e) {
res.status(400).send(e)
}
}, (error, req, res, next) => {
res.status(400).send({
error: error.message
})
})
And I have the binary data of the image like this in front end:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAIQAABtbnRyUkdCIFhZWiAAAAAAAAAAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAA
In the tutorial it shows us that we can send a image via postman like this:
I used this to do the same thing as tutorial did in postman using fetch api with no luck:
const data = new FormData();
data.append("upload", image); // the image is the binary data I showed you
fetch('/accounts/upload', {
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json'
// },
method: 'post',
body: data,
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log(error));
But I get 400 (Bad Request) each time!!
How can I fix this?
I figured out that req.body is empty object like : {} So I think there is something wrong with fetch maybe
EDIT 2: Here is a log from data inside:
function uploadImage(image) {
const data = new FormData();
data.append("upload", image);
console.log(data); // added this to log the data
fetch('/accounts/upload-image', {
method: 'post',
body: data,
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log(error));
}
Result o the log is:

JavaScript-ReactJS problem with GET fetch request ReactJS

I'm trying to doing a basic GET request from ReactJS app to a Node.js API, but I'm getting a response with status 304. I need get a 200 status to save the response of GET in a variable. (Im running Reactjs app in port 3000 and Nodejs API in port 3300)
Node API:
app.get('/serviciosextras', async (req, res) => {
let connection;
console.log(('Servicios Extras'));
try {
connection = await oracledb.getConnection({
user: 'portafolio',
password: '123',
connectString: "localhost:1521/orcl"
});
const result = await connection.execute(
`SELECT dep.id_departamento,
se.id_servicio,
se.precio_servicio
FROM departamento_servicio_detalle dsd
JOIN departamento DEP ON (dsd.id_departamento = dep.id_departamento)
JOIN servicio_extra SE ON (dsd.id_servicio = se.id_servicio)
ORDER BY 1 ASC`
)
const resultSet = result.rows;
let lista = [];
resultSet.map(obj => {
let serviciosSchema = {
'id_departamento': obj[0],
'id_servicio': obj[1],
'precio_servicio': obj[2]
}
lista.push(serviciosSchema);
});
console.log(lista);
res.json(lista);
connection.close();
} catch (err) {
console.error(err);
}
});
GET request from Reactjs
const getExtraServices = () => {
let endpoint = `${URL}serviciosextras`;
const requestOptions = {
method: "GET",
mode: 'no-cors'
// headers: {
// "Content-Type": "application/json",
// Accept: "application/json"
// },
};
console.log(endpoint);
fetch(endpoint, requestOptions)
.then((res, err) => {
console.log(res);
})
.then(result => {
console.log('fue aqui');
console.log(result);
})
.catch(err => {
console.log('ERROR');
console.log(err);
})
}
Im calling the method from this button:(onClick={getExtraServices()})
<Fab onClick={(e) => {
e.preventDefault();
getExtraServices();
}} variant="extended">
<NavigationIcon style={{marginRight: 'theme.spacing(1)'}} />
Navigate
</Fab>
so... I'm getting this:
Firefox Console when I clicked button to call getExtraServices() res is undefined
Network console of GET request I got a response but the status is 304, so I can't get this from code. :/
Console of Nodejs API this console.log if from console.log(lista) before send the res.json(lista)
Does someone know how can I fix this? I need get the response of the GET request to charge a list in ReactJS app, but I can't because the response has body:null.
Error 304 isn't the problem.
It looks like you are missing a statement to turn your response into JSON.
Here's an example from MDN:
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
In particular:
.then(response => response.json())
In your code:
fetch(endpoint, requestOptions)
.then((res, err) => {
console.log(res); // logging res
// no data being returned here
})
.then(result => {
console.log('fue aqui');
console.log(result); // therefore result is undefined
})
.catch(err => {
console.log('ERROR');
console.log(err);
})

I Need Some Help About Axios Lab in JS

My issue is:
I need to get some data from an API using axios library, but for some cases, it is just not working.
This is a working example:
const RAPIDAPI_API_URL = 'https://cbsservis.tkgm.gov.tr/megsiswebapi.v3/api/parsel/40.89253647288918/29.236472547054294/';
const RAPIDAPI_REQUEST_HEADERS = {
'Content-Type': 'application/json'
};
axios.get(RAPIDAPI_API_URL,{ headers: RAPIDAPI_REQUEST_HEADERS })
.then(response => {
const data = response;
console.log(data);
})
.catch(error => console.error('On create error', error));
But when the value of RAPIDAPI_API_URL is changed to "http://jsonplaceholder.typicode.com/users", it throws the following error:
Network Error
at e.exports (https://unpkg.com/axios#0.19.2/dist/axios.min.js:2:9633)
at XMLHttpRequest.l.onerror (https://unpkg.com/axios#0.19.2/dist/axios.min.js:2:8398)
You have to load the request over https not http. Find sample here
const RAPIDAPI_API_URL = 'https://jsonplaceholder.typicode.com/users';
const RAPIDAPI_REQUEST_HEADERS = {
'Content-Type': 'application/json'
};
axios.get(RAPIDAPI_API_URL,{ headers: RAPIDAPI_REQUEST_HEADERS })
.then(response => {
const data = response;
console.log(data);
})
.catch(error => console.error('On create error', error));

Server cookies lost on page refresh

I tried fetch to call api and passing credentials "include" to header which set cookies from server initially but on page refresh cookies got lost.
public post = async (payload:any, endpoint: string):Promise<any> => {
return new Promise((resolve, reject) => {
console.log(${config.baseUrl}${endpoint})
const URL = ${config.baseUrl}${endpoint};
fetch(URL, {
credentials: 'include',
method: 'POST',
body: JSON.stringify(payload),
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(data => data.json())
.then((data:any) => {
console.log("data", data)
const responsePayload = {
statusCode: data.status,
data: data
};
resolve(responsePayload);
})
.catch((error:any) => {
if (error.response === undefined) {
const errorpayload = {
statusCode: 503,
title: 'network error occured',
parameter: 'Network Error',
};
reject(errorpayload);
} else {
const errors = error.response.data.errors;
const errorPayload = {
statusCode: error.response.status,
data: error.response.data.errors,
};
reject(errorPayload);
}
});
});
};
Better read cookies on login and store it to loaclstorage and from there you can use it the way you want.

Categories

Resources