How do i send a POST request to a link in Javascript? - javascript

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

Related

TypeError on fetch request on "e-raktakosha" web site api

I am new to javascript. I was trying to make an api call.
My code
const options = {
method: 'GET',
headers: {
Authorization: 'Basic dW5kZWZpbmVkOnVuZGVmaW5lZA==',
'content-type': 'application/json',
}
};
fetch(
'https://www.eraktkosh.in/BLDAHIMS/bloodbank/nearbyBB.cnt?hmode=GETNEARBYSTOCKDETAILS&stateCode=21&districtCode=378&bloodGroup=all&bloodComponent=11&lang=0',
options
)
.then((response) => response.json())
.then((response) => console.log(response))
.catch((err) => console.error(err));
but I encountered with an error saying
Error: Failed to fetch
This api call works perfectly with Hoppscotch
If I try to hit the url right on my url bar, it also works fine.
Any help is strongly appreciated. Thank you from Manoranjan
As other People already mentioned, you can't pass a Body when doing a GET HTTP call, instead you can pass Query Params
Notice this part on the URL
hmode=GETNEARBYSTOCKDETAILS&stateCode=21&districtCode=378&bloodGroup=all&bloodComponent=11&lang=0
Still looking into the code it seems the server have a cors policy, look at this sandbox
See this codesandbox -> https://codesandbox.io/s/peaceful-mcclintock-exuzol?file=/src/index.js
Summary:
GET accept body/payload but it could cause errors, see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET
Using the Web API (new headers, new request) for doing the HTTP call
It is better to just avoid sending payloads in GET requests.
Please don't use body with a get request. The GET request is purely meant to collect back data from server, which allows you to sent Queries, not data on the request. Just remove body:'false' or use body:false. The best way is to remove the body from your request so unexpected input is not sent via this GET request.

Get all Products with an API request in BigCommerce

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

API call (fetch) with user token through Javascript (React.js)

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...

Request JS Uri requesting incorrectly

I am trying to POST to a server using Request JS. I am having issues with parts of the path.
return await request.get({
method: 'POST',
uri: `${domain}/info/test/`,
body: bodyAsString,
headers: {
Authorization: `bearer ${token}`,
},
}).pipe(res);
This api has two ways to hit it: /info/test as a POST and /info/test/:GUID as a GET. For some reason, when I hit the API with Request it complains that 'test' is not a valid GUID like I am one level too low on the path. I can hit it in Postman just fine.
you should use request.post instead of request.get

How to Use Javascript's Fetch to get POST Request Data?

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

Categories