I'm quite new to using fetch and I dont know if I'm doing this right since it works fairly well with POST. If I use the normal fetch method, and not the function I made, the server responds with the data. But if I use this, the data becomes undefined. Any ideas on how I can fix this?
network_requests.js
export const getData = (url, data) => {
return fetch(url, {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'include', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json',
'Authorization': 'Token '+ localStorage.token
},
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => response.json()); // parses response to JSON
};
sample usage: (doesnt work)
fetchDrivers() {
return getData('/members/drivers').then(data => {
if (!data["error"]) {
//for each entry in drivers data, append data as a dictionary in tableData
//ant tables accept values {"key": value, "column_name" : "value" } format
//I cant just pass the raw array since its a collection of objects
const tableData = [];
//append drivers with their ids as key
data["drivers"].forEach(item => tableData.push({
"key": item.id,
"name": item.name
}));
this.setState({drivers: tableData});
} else {
console.log(data["error"]);
}
});
}
Related
How to follow redirecting links till the actual body is retried.
That link A redirects to link B using a post request. I am not in charge of the server.
e.g https://www.efcc.gov.ng/career
const setLink = async ({ link, search, config }) => {
setResponce({ status: 'Laoding' });
try {
const resp = await fetch(link, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
// body: JSON.stringify(data) // body data type must match "Content-Type" header
});
//const json = await resp.json(); // parses JSON response into native JavaScript objects
setResponce({ status: 'Laoded rrrrrrrr', data: resp });
} catch (err) {
console.log('received error: ', err.toJSON());
setResponce({ status: 'error Net' });
}
};
I was working on a React APP which fetches data from https://restcountries.com/v2/all and now I have an error.
useEffect(() => {
fetch(`https://restcountries.com/v2/all`)
.then((r) => r.json())
.then((data) => {
if (data !== undefined) {
setCountries(data);
} else {
alert('Can´t Load Data');
}
});
}, []);
**
use this format with header
** ##
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {`enter code here`
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
}, []);
You are getting a CORS error which means target domain of api (restcountries) does not allow other domains to fetch data.
The solution to this problem is a server side browser or headless browser. Like selenium and puppeteer
https://www.selenium.dev/
https://github.com/puppeteer
But i have tested and api is giving me data in browser with same fetch code. I cant reproduce the problem. Its an issue with something else
this is happening due to multiple reason like due to authentication or your are not sending token in request header second due to server down or may be your are passing wrong param to request third one my be this endpoint can me access by only specific domains url.
url---http://eign-backend.herokuapp.com/property/get-property/17/
Do i have to write complete url like till "/17/" or what!
const response=await fetch('url',{
method:'POST',
body: JSON.stringify(
{
//what should I write here
}
),
headers:{
headers: {'Content-Type':'application/json'},
}
})
const data=await response.json();
console.log(data);
}
First argument in fetch is the actual url
const response=await fetch('http://eign-backend.herokuapp.com/property/get-property/17/',{
method:'POST',
body: JSON.stringify(
{
//what should I write here => write whatever you want to send in this post request's body
}
),
headers:{
headers: {'Content-Type':'application/json'},
}
})
const data=await response.json();
console.log(data);
Consider reading some documentation first
You can directly make a POST request on that URL. It's OK to send a POST request without a body and instead use query string parameters but then it should have been a get request instead of POST if there is no need for the body. But be careful if your parameters contain characters that are not HTTP valid you will have to encode them.
var requestOptions = {
method: 'POST',
redirect: 'follow'
};
fetch("http://eign-backend.herokuapp.com/property/get-property/17/", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
This is the fetch call that I have used.
try this
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
I am trying to convert this jQuery call to native Javascript using fetch() as mentioned in MDN (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options).
$.ajax(
{
method: "GET",
url: CB_ABS_URI + "ajax/get-checkin.php",
dataType: "json",
data: { DwellingUnitID:DwellingUnitID },
})
to
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
}
postData(CB_ABS_URI + "ajax/get-checkin.php", { DwellingUnitID: DwellingUnitID })
.then((data) => {
console.log(data); // JSON data parsed by `response.json()` call
});
But I can't seem to send GET data in the body. Is adding the query to ajax/get-checkin.php the only way ?
But I can't seem to send GET data in the body
fetch makes a clear distinction between the query string in the URL and the data in the request body (unlike jQuery which switches between them depending on the request method).
Is adding the query to ajax/get-checkin.php the only way ?
Yes, see the documentation:
If you want to work with URL query parameters:
var url = new URL("https://geo.example.org/api"),
params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)
Im currently struggling to convert a fetch get request to an axios get request.
Here is my fetch request:
window.fetch(url, {
headers: {
'Origin': window.location.origin,
},
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
})
I am trying to convert it to axios, but am struggling to find corresponding attributes for cache and credentials. Anyone have any idea?
caching:
const config = {
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
}
};
const { data } = await axios.get(url, config);
for credentials, check the attribute withCredentials. By default, it is set to false.