I am trying to make a POST request using Javascript's fetch method as described here.
I get a ReadableStream instead of a usual json response, such as what I would get with jQuery, Angular, whatever.
My code is here: https://jsbin.com/vuwilaviva/edit?css,js,output
var request = new Request('https://httpbin.org/post', {
method: 'POST',
mode: 'cors',
data: 'The sky is green',
redirect: 'follow',
headers: new Headers({
'Content-Type': 'text/plain'
})
});
// Now use it!
fetch(request).then(function(resp) {
console.log('Logging response...')
console.log(resp);
});
The test API endpoint works fine with postman, curl, etc, so I am sure I am using fetch wrong, and it's not an issue with the API (it just returns whatever string is passed to it as data):
Edit: The current answer doesn't actually get the data returned by the post request - it's nowhere to be found in the logged json:
response.json should be used for this
fetch(request)
.then(response => response.json())
.then(json => console.log(json));
Related
I've been trying to get this API working on one of my react native project and I keep getting failed to fetch errors.
This is the code
let url = "API endpoint";
let headers = {
Authorization:
"working bearer token"
};
fetch(url, {
method: "GET",
headers: headers,
body: null
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error));
When I try this on a postman, it works just fine and returns correct data.
When the data is coming from API that is [] empty array, the fetch works again. But when there is a large data, I get a fetch error.
How can I solve this issue?
Thank you
EDIT: To add, it is definitely not a CORS issue.
I want to get a list of all the products from my BigCommerce store using an API call. This is the code I have used:
fetch("https://api.bigcommerce.com/stores/##########/v3/catalog/products", {
method: "GET",
mode: "no-cors",
"X-Auth-Token": "###############################",
"Content-Type": "application/json",
Accept: "application/json",
})
.then((res) => res.json())
.then((json) => console.log(json));
I have used the correct store hash and access token but I get this error:
I understand this is a very basic question but I would like some help as I am stuck.
Using the rest client extension and the same credentials, I am able to get the list of products:
I believe you're missing the headers object as well as missing quotes around Accept. Also, if you're running this on the client side, this will not work, as you 'd need make a server side API request to get all products. To do so, you will need to make the API request to some middleware application.
In addition to making the request on the server side, try modifying it a bit to look like this:
fetch(`url`,{
method: 'GET',
headers: {
'X-Auth-Token': '<token>',
'Content-Type': 'application/json',
'Accept': `application/json`
}
})
.then((res) => res.json())
.then((json) => console.log(json));
how are you guys doing??
I'm trying to fetch data (in React with JS) from a website X (that has cors-enabled) but need first to get a user token from a website Y and I don't know how to figure that out. Somehow I think that I have to get the user token from Y, save it in a variable and add it as a header on the other call but I'm kinda lost with the GET/POST methods.
By now what I have is this but somehow doesn't work, I think I'm not sending properly the head or making the actual calls correctly:
getToken(){
const url = 'websiteOfTheToken';
const response = await fetch(url);
const data = await response.json();
this.setState({
userToken: data.image
});
}
And:
getData(){
const response = await fetch('websiteOfTheData', {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'accept': 'application/json',
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify({
title: '' // I don't know what is this doing
})
}).catch( error => {
console.log('Error fetching and parsing data ', error)
});
this.setState({
data: response.json()
});
}
Thank you in advance!!
A few things I want to say / ask about:
Typically you get the token after a successfull login, so a standard request for a token would be a post request with the user data.
An await in javascript works only inside async functions, read about it.
The most common practice for handling api responses (Promise) is to use then-catch blocks, read about it.
A typical JWT header you need to attach to your requests looks like this: "Authorization": "Bearer theactualtoken1234".
The body of the fetch post request is the actual data you're sending to the server. So its contents are totally arbitrary - I also don't have an idea what this "title": "" is doing...
I have 1 json file: { "clicks": 0 }
I'm trying to retrieve the data from it and then update it. The GET works, but the PUT does not.
I use Typescript which should not be a problem:
const getClickCounterJsonData = () => fetch(
'click-counter.json',
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
}
)
.then(response => response.json())
.then(myJson => myJson);
// this call is actually added to onClick, but you get the idea
getClickCounterJsonData().then(data => console.log(data['clicks'])); //this works, returns the actual value of the clicks property
Now the not working updating function:
const updateClickCounterJsonData = (newData: any) => fetch(
'click-counter.json',
{
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(newData)
}
)
.then(response => response.json())
.then(myJson => myJson);
// again in a onClick function
updateClickCounterJsonData({ clicks: 5 }).catch(error => console.log(error)); // this returns SyntaxError: Unexpected token < in JSON at position 0
// and also the request in the Network tab says 404 Not Found with a preview text: Cannot PUT click-counter.json
Am I not allowed to do PUT requests to a json resource? I'm not super familiar with the topic, but found a lot of resources that this should be possible. The GET works as expected and the PUT seems to be well configurated but I don't know why it doesn't work.
Am I missing something?
Servers may route requests based on the HTTP request type - for example express/node.js server provides explicit methods to process PUT, POST and GET requests using app.put, app.post and app.get respectively. The logic of this comes under the umbrella of "request routing". If no route is encountered that matches a request pattern, typically the router is coded to fall through to server code that responds with a 404 error.
Hence you can't just change a GET request that works into a PUT request and expect the server to adapt - it would need code changes to do so.
I am trying to send a POST request to a link as its written in weGWRGWRG documentation, i did it with postman and in WEGWegw but i am not able to find out how to do it in wegwEGWEGWG.
To WegweGEG an Event
Make a POwegwG ST or EWgwE GWgwegweb request to:
url = 'https://kajglakerjglekarjglkearjg'
i did it in weGWe gw using aregerajkgearkgnkjernvkjeangkjnearhl)
But i wanted to do in normal javascript tried but not able to figure out.
You can use the Fetch API in JavaScript (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
See Example Below:
fetch('https://maker.ifttt.com/trigger/notifier/with/key/hereGoesMyKey', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({foo: 'bar'})
}).then(res => res.json())
.then(res => console.log(res));