I´m refering to this post: Fetch: POST JSON data
I´ve copied the code which is linked down below.
My question is, is it possible to save for example "Content-Length" which i get as a response in the JSON-file as a variable with which i can continue to work?
Looking forward!
Thanks already!
fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
}).then(res => res.text())
.then(res => console.log(res));
And my result is:
{
"args": {},
"data": "{\"a\":7,\"str\":\"Some string: &=&\"}",
"files": {},
"form": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "br, gzip, deflate",
"Accept-Language": "*",
"Content-Length": "32",
"Content-Type": "application/json",
"Host": "httpbin.org",
"Sec-Fetch-Mode": "cors",
"User-Agent": "undici",
"X-Amzn-Trace-Id": "Root=1-6388fb1d-3f7791960bdce04f36356182"
},
"json": {
"a": 7,
"str": "Some string: &=&"
},
"origin": "79.208.157.109",
"url": "https://httpbin.org/post"
}
Of course you can - just access it and store it in a variable:
const example = async() => {
const res = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
})
const response = await res.json()
const contentLength = response.headers['Content-Length'];
displayContentLength(contentLength);
}
function displayContentLength(length) {
console.log('The content length is: ' + length);
}
example();
Related
I am trying to create a search page for Pathfinder. Below is the code I wrote to try and pull in the data from the api. While trying to just get the fetches to work, I am noticing when I console.log the data returned from the fetches, it is listed more than once.
async function getData(){
const apiKey = "API KEY WITHHELD";
const actionsURL = "https://api.pathfinder2.fr/v1/pf2/action";
const ancestriesURL = "https://api.pathfinder2.fr/v1/pf2/ancestry";
const ancestryFeaturesURL = "https://api.pathfinder2.fr/v1/pf2/ancestryFeature";
const archetypesURL = "https://api.pathfinder2.fr/v1/pf2/archetype";
const backgroundsURL = "https://api.pathfinder2.fr/v1/pf2/background";
const classesURL = "https://api.pathfinder2.fr/v1/pf2/class";
const classFeaturesURL = "https://api.pathfinder2.fr/v1/pf2/classFeature";
const deitiesURL = "https://api.pathfinder2.fr/v1/pf2/deity";
const equipmentURL = "https://api.pathfinder2.fr/v1/pf2/equipment";
const featsURL = "https://api.pathfinder2.fr/v1/pf2/feat";
const spellsURL = "https://api.pathfinder2.fr/v1/pf2/spell";
// Actions
const actionsResponse = await fetch(actionsURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const actionsData = await actionsResponse.json();
// Ancestries
const ancestriesResponse = await fetch(ancestriesURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const ancestriesData = await ancestriesResponse.json();
// Ancestry Features
const ancestryFeaturesResponse = await fetch(ancestryFeaturesURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const ancestryFeaturesData = await ancestryFeaturesResponse.json();
// Archetypes
const archetypesResponse = await fetch(archetypesURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const archetypesData = await archetypesResponse.json();
// Backgrounds
const backgroundsResponse = await fetch(backgroundsURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const backgroundsData = await backgroundsResponse.json();
// Classes
const classesResponse = await fetch(classesURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const classesData = await classesResponse.json();
// Class Features
const classFeaturesResponse = await fetch(classFeaturesURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const classFeaturesData = await classFeaturesResponse.json();
// Deities
const deitiesResponse = await fetch(deitiesURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const deitiesData = await deitiesResponse.json();
// Equipment
const equipmentResponse = await fetch(equipmentURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const equipmentData = await equipmentResponse.json();
// Feats
const featsResponse = await fetch(featsURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const featsData = await featsResponse.json();
// Spells
const spellsResponse = await fetch(spellsURL, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Access-Control-Allow-Headers": "*",
"Content-Type": 'application/json',
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
});
const spellsData = await spellsResponse.json();
// do what you want with actionsData and ancestriesData, etc here
console.log(actionsData);
console.log(ancestriesData);
console.log(ancestryFeaturesData);
console.log(archetypesData);
console.log(backgroundsData);
console.log(classesData);
console.log(classFeaturesData);
console.log(deitiesData);
console.log(equipmentData);
console.log(featsData);
//console.log(spellsData);
}
getData();
Originally I used a fetch to grab all of the endpoints listed in the main endpoint (see page: https://api.pathfinder2.fr/doc) and then ran a loop to fetch data from each endpoint -- DRY principles and what not.
const apiKey = "API KEY WITHHELD";
let pathfinderLibraries = [];
let pathfinder = fetch("https://api.pathfinder2.fr/v1/pf2", {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
}).then((response) => {
return response.json()
})
.then(data => {
let pflibraries = data;
//console.log(pflibraries);
pflibraries.forEach(pflibrary => {
pathfinderLibraries.push(pflibrary);
pathfinderLibraries.forEach( library => {
fetch(library, {
'method': 'GET',
'headers': new Headers({
"Authorization": apiKey,
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
}),
}).then((response) => {
return response.json()
}).then(data => {
console.log(data);
});
});
console.log(pflibrary);
});
});
But this was logging each of the endpoint data multiple times so I decided to try it without the loop. This decreased the amount of times each endpoint data was logged, but the data was still being logged multiple times.
I experimented with changing the location of the console.logs and had 1 of 2 results, either it did not log at all or continued to log multiple times.
As I said previously, I just wanted to create a function with a loop that would iterate through main endpoint that lists the sub-endpoints and fetch the data so I can create a search page for Pathfinder.
In this block of code
pflibraries.forEach(pflibrary => {
pathfinderLibraries.push(pflibrary);
pathfinderLibraries.forEach( library => {
you traverse through pflibraries and each of them you are adding into pathfinderLibraries. Right after that you traverse through pathfinderLibraries.
This means that after every loop through pflibraries your list of libraries in pathfinderLibraries will contain pflibrary from the current iteration and also from all the previous iterations of pflibraries.
To fix the problem you need to remove this forEach from the code
pathfinderLibraries.forEach( library => {
and just call the fetch for the library in the current iteration.
I want to call the API POST method with axios, I did it with postman with header configuration like, and it return the results
and the body request looks :
it return error when I call by axios this my script, anyone can help me what I suppose todo from the axios side ?
const header = {
headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
}
axios({
method: 'POST',
url: URL,
headers: header,
data : {
}
})
.then((response) => {
if (response.status !== 200) {
return res.send(respone("500", response.data.result.data))
} else {
return res.send(respone("200", response.data.result.data))
}
})
.catch((error) => {
console.log(error);
return res.send(error)
})
the error show
{
"message": "Request failed with status code 404",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Content-Transfer-Encoding": "application/json",
"HTTP_API_KEY": "xxxx",
"User-Agent": "axios/0.27.2",
"Content-Length": 2
},
"method": "post",
"url": "xxxxx",
"data": "{}"
},
"code": "ERR_BAD_REQUEST",
"status": 404
}
It seems you nested your headers inside another "headers" property.
Basically you're doing this
headers: {
headers: {
'Content-Transfer-Encoding': ...
}
}
As Zai showed in her answer you problem is your header variable:
const header = {
headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
}
is nested, when you do this:
axios({
method: 'POST',
url: URL,
headers: header,
data : {
}
what you are really doing is:
axios({
method: 'POST',
url: URL,
headers: headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
},
data : {
}
So your header: instead of being Content-transfer etc... is just 'headers'
try this:
const header = {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
also, i recommend you to do a console.log with your api call in order to find this problems faster and compare with postman, really helpful in develop phase (just use it in local, never push that log to production)
I use axios to send a POST HTTP request with some binary data like this:
axios.post(url, input, {headers: {'Content-Type': 'application/octet-stream'}})
When I got an Bad request error I printed out the request headers:
"headers" : {
"common": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/octet-stream"
},
"delete": {},
"get": {},
"head": {},
"post": {
"Content-Type": "application/octet-stream"
},
"put": {
"Content-Type": "application/x-www-form-urlencoded"
},
"patch": {
"Content-Type": "application/x-www-form-urlencoded"
}
}
I overrode the default headers (see below) and got Ok instead Bad request
axios.defaults.headers = {"Content-Type": "application/octet-stream"}
So the problem is fixed but I don't like overriding axios defaults. How would you suggest use axios.post to send the header correctly ?
I am working on implementation of strava in my website. I am new to JavaScript and I am not understanding whether I am doing it correctly or not. My problem is I am unable to get access token from JSON response. I don't know why. Please Help me.
the resonse what I am getting
code
<script>
const auth_link = "https://www.strava.com/oauth/token"
function getActivites(res){
console.log('response2',res.json());
const activities_link = `https://www.strava.com/api/v3/athlete/activities?access_token=${res.access_token}`
fetch(activities_link)
.then((res) => console.log(res.json()))
}
function reAuthorize(){
fetch(auth_link,{
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: 'xxxx',
client_secret: 'xxxxx',
refresh_token: 'xxxxx',
grant_type: 'refresh_token'
})
})
.then(res => {
var response = res.json();
var access_token = response.access_token;
console.log('response',access_token)
// getActivites(res)
})
}
reAuthorize()
</script>
I am getting access token as undefined
function reAuthorize() {
fetch(auth_link, {
method: "post",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
},
body: JSON.stringify({
client_id: "55077",
client_secret: "801a8541e8ae55cffee584a48c5bb6a233dea9a0",
refresh_token: "08342cdf3250da9e0d1b53303fa40faf0d05965d",
grant_type: "refresh_token"
})
}).then(response => response.json())
.then(data => console.log(data));
}
how to handle request header accept application/ld+json in react.js get request
Media type
application/id+json
Controls Accept header.
i am getting unauthorized 401 error dont know why can anyone please explain me i am facing this type of error for the first time .
function parseJwt(token) {
if (!token) { return; }
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
}
export async function getRequest(url , token){
let token_data = parseJwt(token)
console.log('Token data ', token_data)
let response = await fetch(API_URL(url), {
method: "GET",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Accept": `application/${token_data.id}+json`,
// 'Content-Type': `application/${token_data.id}+json`,
// "Authorization": JSON.stringify(token_data)
},
redirect: "follow",
referrer: "no-referrer",
})
return response
}
Please Try Below code
var token = 'XXXXX-XXXX-XXXXX';
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': token
},
body: payLoad,
})