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));
Related
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:
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 use this code to fetch a token successfully if I run it from node. However, it fails, and I notice the body received in the server end is empty when I run it in React Native. What is wrong in React Native?
function fetchToken() {
console.log("fetchToken");
const fetch = require("node-fetch");
const params = new URLSearchParams();
params.append('client_id', '1234567');
params.append('client_secret', 'abcdefg');
const url = "https://example.com/token";
var headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
fetch(url, {method: 'POST', headers: headers, body: params})
.then(response => response.json())
.then((resp) => {
console.log(resp);
})
.catch(error => console.error('Unable to fetch token.', error));
console.log("fetchToken done");
}
i am fetching some data by using POST api call in which i have data and a token value for header, but i am getting bad response and i checked many docs but can't figure out the error, here is the code:
export const shareUserProfileHandler = (sharedReceiverData) => {
return dispatch => {
let formData = new FormData();
for (let key in sharedReceiverData) {
formData.append(key, sharedReceiverData[key]);
}
let requestConfig = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': 'Token 97a74c03004e7d6b0658b14ddb'
},
body: formData
};
fetch(`http://api.com`, requestConfig)
.then(response => response.json())
.then(response => {
alert('share user card api worked')
})
.catch(error => {
alert('api error ' + error)
})
}
};
the above is catching error and showing - SyntaxError: JSON Parse error: Unrecognized token'<'
Your response doesn't seem to be a JSON.
Replace
.then((response) => response.json())
For
.then((response) => { console.log('response', response); response.json() })
And check what is wrong with the response before the error.
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);