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);
})
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:
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));
With the following I get the expected response.data value:
axios({
method,
url
}).then(response => { console.log(response) })
However, when I add the transformResponse property as follows I get a response.data value of undefined:
axios({
method,
url,
transformResponse: [(data) => {
return data
}]
}).then(response => { console.log(response) })
Can someone please tell me what I'm missing here! Thanks
I suggest you to use interceptors since they are more clean
Interceptors work as a middlware on your requests
remove transformResponse and add this
axios.interceptors.response.use(function (response) {
return response.data;
});
axios({
method,
url,
}).then(response => { console.log(response) })
You can check the below sample to safe parse. transformResponse get data as raw staring so u can parse it.
const instance = axios.create({
baseURL: baseURL,
transformResponse: [
(data) => {
let resp;
try {
resp = JSON.parse(data);
} catch (error) {
throw Error(
`[requestClient] Error parsingJSON data - ${JSON.stringify(
error
)}`
);
}
if (resp.status === "success") {
return resp.data;
} else {
throw Error(`Request failed with reason - ${data}`);
}
},
],
});
Else you can use an interceptor to simplify it.
//const axios = require("axios");
const jsonInterceptor = [
(response) => response.data,
(error) => Promise.reject(error),
];
function jsonClient() {
const client = axios.create();
client.interceptors.response.use(...jsonInterceptor);
return client;
}
// Page 1
const jhttp = jsonClient();
jhttp
.get("https://jsonplaceholder.typicode.com/todos/1")
.then((data) => console.log(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
For anyone wondering here is the response:
axios.get(url, {
headers: {
'Content-Type': 'application/json'
},
transformResponse: axios.defaults.transformResponse.concat((data) => {
console.log(data) // this should now be JSON
})
})
from https://github.com/axios/axios/issues/430#issuecomment-243481806
I have to set an header in api call. My POST API calls are working fine. But in my get api calls, header is not getting set.
return fetch('http://api-call.com', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'custom-security':'XXXX',
'Purchase-Code':'XXXXXXX',
'Content-Type':'application/json',
'Cache-Control':'max-age=640000'
}
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
You should setup a Request object and pass your headers wrapped into a Headers object, like:
var request = new Request('http://api-call.com', {
method: 'GET',
headers: new Headers({
'Accept': 'application/json',
'custom-security':'XXXX',
'Purchase-Code':'XXXXXXX',
'Content-Type':'application/json',
'Cache-Control':'max-age=640000'
})
});
Then just invoke fetch with your request as parameter:
fetch(request)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
Check reference
2021 answer: just in case you land here looking for how to make GET and POST Fetch api requests using async/await or promises as compared to axios.
I'm using jsonplaceholder fake API to demonstrate:
Fetch api GET request using async/await:
const asyncGetCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncGetCall()
Fetch api POST request using async/await:
const asyncPostCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
});
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncPostCall()
GET request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
POST request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
})
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
GET request using Axios:
const axiosGetCall = async () => {
try {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosGetCall()
Authenticated POST request using Axios:
const axiosPostCall = async () => {
try {
const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts', {
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
},{
headers: {
Authorization:
`Bearer ${token}`
}
})
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosPostCall()
In my application, I have a simple fetch for retrieving a list of users which sends over an authentication token to an API
fetch("/users", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
token: this.props.getUser().token
})
})
.then(res => res.json())
.then(users => this.setState({ users }))
.catch(err => {
console.error(err);
});
However, the API may return a 401 error if the token is expired.
How do I handle it properly in the fetch so that the state is only set when the response is succesful?
A cleaner way to handle success/error of a fetch response would be to use the Response#ok readonly property
https://developer.mozilla.org/en-US/docs/Web/API/Response/ok
fetch('/users').then((response) => {
if (response.ok) {
return response.json();
}
throw response;
}).then((users) => {
this.setState({
users
});
}).catch((error) => {
// whatever
})
res inside callback function in your first .then function contains a key called status which holds the request status code.
const url = 'https://api.myjson.com/bins/s41un';
fetch(url).then((res) => {
console.log('status code:', res.status); // heres the response status code
if (res.status === 200) {
return res.json(); // request successful (status code 200)
}
return Promise.reject(new Error('token expired!')); // status code different than 200
}).then((response) => console.log(response));