Limit fetch results from javascript fetch - javascript

Is there a function similar to q=sort& or q=created:& to limit number of results from a JavaScript fetch?
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.json())
.then((data) => { }

The best solution, of course, is if the https://jsonplaceholder.typicode.com/posts endpoint documents a limit or filter parameter you can send it.
Assuming the result is an array, or contains an array, the very-much-second-best solution is to filter the result (to apply criteria) and/or slice the result (to just apply a limit):
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.json())
.then((data) => {
data = data.filter(entry => entry.created > someValue) // Created after X
.slice(0, 1000); // Limit to 1000
// ...use data...
})
.catch(error => { // <=== Don't forget to handle errors
// Handle error...
});
Note: Your fetch call is missing a check on res.ok (it's not just you, a lot of people make that mistake so many that I wrote it up on my anemic little blog):
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => { // ***
if (!res.ok) { // ***
throw new Error("HTTP error " + res.status); // ***
} // ***
}) // ***
.then((res) => res.json())
.then((data) => {
data = data.filter(entry => entry.created > someValue)
.slice(0, 1000);
// ...use data...
})
.catch(error => {
// Handle error...
});

From https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch:
postData(`http://example.com/answer`, {answer: 42})
.then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
.catch(error => console.error(error));
function postData(url = ``, data = {}) {
// Default options are marked with *
return 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; charset=utf-8",
// "Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
.then(response => response.json()); // parses response to JSON
}
Not sure what exactly you want so here are 3 possibilities:
You can add a payload to the body of the fetch, see above.
You could simply url-encode it.
On res.json()) .then((data) => { } ... You can filter the data you want.
Hope this helps.

Related

how to fetch data from this api using 'POST' method in javascript

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
});

Refactor switch case into its own class method. How?

I have a wrapper class for fetch promises and I wanted to console out http response statuses.
Currently the switch is inside the get() method. How can I shift this switch case into the error() method and use it as a "thenable"?
Take a look:
class CustomFetch {
get(url) {
return new Promise((resolve, reject) => {
const getOptions = {
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/x-www-form-urlencoded',
'Content-Type': 'application/json',
// 'Content-Type': 'text/xml'
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
// body: JSON.stringify(params) // body data type must match "Content-Type" header
};
// DO FETCH
fetch(url, getOptions)
.then(function(res) {
// RESPONSE VALIDATION
switch (res.status) {
case 200:
// code...
console.info('HTTP GET response status:', res.status, 'OK');
break;
case 201:
// code...
console.info('HTTP GET response status:', res.status, 'Created');
break;
case 404:
// code...
throw new Error('HTTP GET response status: 404 Not Found.');
break;
case 500:
// code...
throw new Error('HTTP GET response status: 500 Internal Server Error.');
break;
case 503:
// code...
throw new Error('HTTP GET response status: 503 Service Unavailable.');
break;
default:
// code...
break;
}
return res;
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err));
});
}
error(res) {
// Here, for example..
}
}
const http = new CustomFetch;
async function Run() {
// GET -> AWAIT...
const fetch1 = await http.get('https://jsonplaceholder.typicode.com/users/1')
.then(data => console.log(data))
.then(data => console.log('asycn/await: Resource Get Successful.'))
.then(data => console.log('_'))
.catch(err => console.log(err));
}
// RUN async /await fetch functions in procedural order.
Run();
If I understand what you are asking properly, you want to move the switch statement out into the error method on the class?
Because it is in the promise chain the error method would need to return a promise.
Maybe something like the following would work:
error(res) {
switch (res.status) {
case 200:
// code...
console.info('HTTP GET response status:', res.status, 'OK');
break;
case 201:
// code...
console.info('HTTP GET response status:', res.status, 'Created');
break;
case 404:
// code...
throw new Error('HTTP GET response status: 404 Not Found.');
break;
case 500:
// code...
throw new Error('HTTP GET response status: 500 Internal Server Error.');
break;
case 503:
// code...
throw new Error('HTTP GET response status: 503 Service Unavailable.');
break;
default:
// code...
break;
}
return res.json();
}
You would also need to remove this statement:
.then(res => res.json())
that follows the call.
So your get method would now look like:
(EDIT: As it has been pointed out, we must try to avoid the explicit constructor antipattern, so we would instead return the entire promise and defer the resolution and rejection to the caller)
// code above the fetch...
return fetch(url, options)
.then(this.error);
Here is the updated code to reflect the removal of explicit construction anti-pattern. This is thanks to Patrick's second comment.
This class contains GET, POST, PUT & DELETE.
The class uses fetch. Then you use async await functions to return them in order.
class CustomFetch {
// METHOD: GET
get(url) {
const getOptions = {
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/x-www-form-urlencoded',
'Content-Type': 'application/json',
// 'Content-Type': 'text/xml'
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
// body: JSON.stringify(params) // body data type must match "Content-Type" header
};
// DO FETCH
return fetch(url, getOptions)
.then(this.getResStatus)
}
// ================================================================================
// METHOD: POST
post(url, params) {
const postOptions = {
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/x-www-form-urlencoded',
'Content-Type': 'application/json',
// 'Content-Type': 'text/xml'
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
body: JSON.stringify(params) // body data type must match "Content-Type" header
};
// DO FETCH
return fetch(url, postOptions)
.then(this.getResStatus)
}
// ================================================================================
// METHOD: PUT
put(url, params) {
const putOptions = {
method: 'PUT', // *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/x-www-form-urlencoded',
'Content-Type': 'application/json',
// 'Content-Type': 'text/xml'
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
body: JSON.stringify(params) // body data type must match "Content-Type" header
};
// DO FETCH
return fetch(url, putOptions)
.then(this.getResStatus)
}
// ================================================================================
// METHOD: DELETE
delete(url) {
const deleteOptions = {
method: 'DELETE', // *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/x-www-form-urlencoded',
'Content-Type': 'application/json',
// 'Content-Type': 'text/xml'
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
// body: JSON.stringify(params) // body data type must match "Content-Type" header
};
// DO FETCH
return fetch(url, deleteOptions)
.then(this.getResStatus)
}
// ================================================================================
// METHOD: GET RESPONSE
getResStatus(res) {
switch (res.status) {
case 200:
// code...
console.info('HTTP response status:', res.status, 'OK');
break;
case 201:
// code...
console.info('HTTP response status:', res.status, 'Created');
break;
case 404:
// code...
throw new Error('HTTP response status: 404 Not Found.');
break;
case 500:
// code...
throw new Error('HTTP response status: 500 Internal Server Error.');
break;
case 503:
// code...
throw new Error('HTTP response status: 503 Service Unavailable.');
break;
default:
// code...
break;
}
// CONVERT TO JSON...
return res.json();
}
} // end Class {}
const http = new CustomFetch;
async function Run() {
// ================================================================================
// GET -> AWAIT...
const fetch1 = await http.get('https://jsonplaceholder.typicode.com/users/1')
.then(data => console.log(data))
.then(data => console.log('ASYNC/AWAIT: Resource Get Successful.'))
.then(data => console.log('|'))
.catch(err => console.log(err));
// ================================================================================
// POST data
const postData = {
name: 'Mark Postman',
username: 'markpostman',
email: 'mpostman#email.com'
}
// POST -> AWAIT...
const fetch2 = await http.post('https://jsonplaceholder.typicode.com/users', postData)
.then(data => console.log(data))
.then(data => console.log('ASYNC/AWAIT: Resource Post Successful.'))
.then(data => console.log('|'))
.catch(err => console.log(err));
// ================================================================================
// PUT data
const putData = {
name: 'Mark Putman',
username: 'markpostman',
email: 'mpostman#email.com'
}
// PUT -> AWAIT...
const fetch3 = await http.put('https://jsonplaceholder.typicode.com/users/1', putData)
.then(data => console.log(data))
.then(data => console.log('ASYNC/AWAIT: Resource Put Successful.'))
.then(data => console.log('|'))
.catch(err => console.log(err));
// ================================================================================
// DELETE -> AWAIT...
const fetch4 = await http.delete('https://jsonplaceholder.typicode.com/users/1')
.then(data => console.log(data))
.then(data => console.log('ASYNC/AWAIT: Resource Delete Successful.'))
.then(data => console.log('|'))
.catch(err => console.log(err));
}
// RUN async /await fetch functions in procedural order.
Run();

How to retrieve token from script

I have the following script:
let url = window.location.href;
const token = {
authorization(url){
authentication_code = url.split("?")[1].split("&")[1].split("=")[1];
this.postData("https://www.strava.com/oauth/token?grant_type=authorization_code&client_id=3035dd7&client_secret=3db4fddd039117f8029b406fe72669a4472594bfb6b&code=" + authentication_code)
.then(data => data.access_token) // JSON-string from `response.json()` call
.catch(error => console.error(error));
},
postData(url = "") {
return fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
})
.then(response => response.json()); // parses response to JSON
}
};
This script should authorize a client to strava and retrieve a token for further usage. Somehow I'm not able to understand how to get the token out of the const token.
when I call token.authorization(). It will authorize. But I have no idea how to retrieve the data.access_token from the function.
Thanks.
A simple return statement could be used before this.postData and you would send the token in the promise.
let url = window.location.href;
const token = {
authorization(url){
authentication_code = url.split("?")[1].split("&")[1].split("=")[1];
return this.postData("https://www.strava.com/oauth/token?grant_type=authorization_code&client_id=3035dd7&client_secret=3db4fddd039117f8029b406fe72669a4472594bfb6b&code=" + authentication_code)
.then(data => data.access_token) // JSON-string from `response.json()` call
.catch(error => console.error(error));
},
postData(url = "") {
return fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
})
.then(response => response.json()); // parses response to JSON
}
};
and when calling, you get a promise in return with the token, so
token.authorization(url).then(tokenFromResponse=>console.log(tokenFromResponse));
Now you can use the token as desired.

Adding a user using fetch with POST method

Using the following code, I'm trying to add a new user and console log all users including the new added one:
const url = "https://jsonplaceholder.typicode.com/users";
// Creating a user
fetch(url, {
method: "POST",
body: JSON.stringify({
name: "Robert Miller",
username: "robby",
email: "roby#outlook.com"
}),
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(response => console.log(response));
However, the console.log shows only the added user but not all users.
My assumption was that because the method of the fetch is POST, I need to send another request via GET to get all users and came up with this:
const url = "https://jsonplaceholder.typicode.com/users";
// Creating a user
fetch(url, {
method: "POST",
body: JSON.stringify({
name: "Robert Miller",
username: "robby",
email: "roby#outlook.com"
}),
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(response => console.log(response));
fetchAllUsers();
function fetchAllUsers() {
fetch(url)
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
// Read the response as json.
return response.json();
})
.then(data => {
// Do stuff with the JSON
console.log(data);
})
.catch(error => {
console.log("Looks like there was a problem: \n", error);
});
}
But I still cannot see the added user in the list. Any help?
I think this link is answer your question:
Unable to post a new user
Since JSONPlaceholder is a shared API used by many, modifications are faked (POST, PUT, PATCH) and resources are read-only. This is to avoid user "A" creating new resources and having user "B" impacted by them.
If you need to make changes and persist them between calls, you can run JSON Server locally.

CORS issue while trying to get data from a clip on Vimeo using the api/oEmbed

I am using fetch to get the data.
Like so:
getClipMetadata = (url) => {
const endpoint = 'http://www.vimeo.com/api/oembed.json';
fetch(`${endpoint}?url=${encodeURIComponent(url)}`, {
method: 'get',
cache: 'no-cache',
mode: 'cors',
headers: new Headers({
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
})
})
.then((response) => { return response.json();})
.then((res) => console.log("async response received", res))
.catch((err) => console.log("ajax error -> ", err))
}
So the error I get is this:
Response for preflight is invalid (redirect)
I thought it looked quite simple from Vimeo's developer page.
What am I doing wrong?
The endpoint is 'https://vimeo.com/api/oembed.json' rather than 'http://www.vimeo.com/api/oembed.json' and the headers I was sending were causing problems too.
So the final working code looks like this:
getClipMetadata = (url) => {
const endpoint = 'https://vimeo.com/api/oembed.json';
fetch(`${endpoint}?url=${encodeURIComponent(url)}`, {
method: 'get',
cache: 'no-cache',
mode: 'cors',
})
.then((response) => { return response.json();})
.then((res) => console.log("async response received", res))
.catch((err) => console.log("ajax error -> ", err))
}

Categories