Unable to pass Headers parameter in reactjs by using Fetch() - javascript

Stuck in unable to pass headers parameter in fetch call, I tried many different codes snippets by using Stackoverflow as well as Postman code too.
Currently here's the code Snippet for calling GET request by using Fetch method in reactjs
var myHeaders = new Headers();
myHeaders.append("mode", "no-cors");
myHeaders.append("Authorization", "Bearer oauth 2 token");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("api url", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Hi everyone,
I'm calling simple calling GET api by using Fetch function, but request Header is unable to pass in the request. But the same request I'm calling from PostMan it's working.
Any idea where I'm doing wrong.

Related

How to send body through xmlhttprequest for a POST request?

I am trying to send a POST xmlhttprequest for Basic Authentication request. The response is an auth token which i need to use. I am defining the username and password and also sending a body. But whenever i execute the below code through Javascript, it gives me a 401 error. But when i send a request through postman, it gives me the expected output. I even tried taking the code directly from postman but it still gives me a 401 error. Below is the code i am executing -
var jsonToSend = {
'grant_type':'client_credentials'
};
var client_id= 'usernameTest';
var secret_key= 'PasswordTest';
var token_url = 'urlTest';
let xhr2 = new XMLHttpRequest();
xhr2.open("POST",token_url);
//xhr2.setRequestHeader("Authorization","Basic "+btoa(client_id+":"+secret_key));
xhr2.setRequestHeader("Authorization","Basic "+(client_id+":"+secret_key));
xhr2.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//xhr2.send(jsonToSend);
/* xhr2.send(JSON.stringify({
'grant_type':'client_credentials'
}));*/
xhr2.send("grant_type=client_credentials");
I have tried sending the body in different formats (which i have commented out in the above code) but it gives me a 401 error everytime.
Below is the postman generated code -
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic btoa");
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("grant_type", "client_credentials");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("urlTest", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
The postman code also gives 401 error when i try to execute it in my Javascript file. But in postman, POST call works properly.
I am sorry i cannot give out the credentials and url. I feel this is an issue in the way i am sending the body (which is grant_type:client_credentials).
Below is the screenshot from postman.
Any help would be appreciated.

Time synchronisation advices for requests in JS

I need to send multiple requests to a server. But my headers are dynamic and depend on the result of the previous request.
I use fetch to send my request, which is asynchronous. for exemple:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
function server_time() {fetch("myserver/time", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));}
console.log(server_time)
So In this example result is displayed to the console whenever I call FetchTime(). Ok, this is fine. But, this result in my specific application is the server time. I need then to insert it in another Header.
I also need to check the time before each request.
Right now I can't get the result out of my function FetchTime because it is asynchronous and the rest of my code will be executed before. I tried to use async/await. But still, end up with the same result.
Is there a way to execute the rest of my code only after the previous example or should I try with XMLHttpRequest which is synchronous?

Fetch data from Api in react

I want to fetch the data from this api (refer the screenshots) in reactjs using fetch function..I tried different ways but none of them is working
I am doing this way
useEffect(() => {
// POST request using fetch inside useEffect React hook
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ "firebase_id":"fonnnnjnvQXzyOcXK5kW88PM8jnjnhnhb1"})
};
fetch('demo.revon.com/audi/zero/li', requestOptions)
.then(response => response.json())
.then(data => console.log(data));
You should try to call your API without https://localhost:3000 in front of your API link.
You forgot to put HTTP or HTTPS so it consider a subfolder of localhost:3000.
You must do something like that : (or http if not https)
fetch('https://demo.revon.com/audi/zero/li', requestOptions)
.then(response => response.json())
.then(data => console.log(data));
Regards
You’ll need to mention https:// in the fetch url
requestOptions is not the issue here!
You are OBVIOUSLY hitting the localhost domain, not demo.revon.
Insert the full URL: https://demo.revon.com/audi/zero/li

Request to Google Apps Scripts Implementation works from Postman but not from javascript

I have this script defined for a google sheet in Apps Script:
function doPost(e) {
var app = SpreadsheetApp.getActive();
var sheet = app.getSheetByName('Web');
var content = JSON.parse(e.postData.contents)
sheet.getRange("A1").setValue(content);
return ContentService.createTextOutput("Saved");
}
I Implemented it as Web Application and set the access to Anyone.
Then tried sending post request through postman to the generated url and it worked flawlesly. Also tried other postman like apps. Everything without issues. The content body of the request is always stored in the "A1" cell.
But when I want to send exactly the same request using Fetch API from my Vue.js web app. It fails with error: TypeError: Failed to fetch. Nothing else can be read from the error. No status code, nothing.
Body of the function that is called on button click from my web app:
function sendForm() {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"test": "testing from vue"
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://script.google.com/macros/s/<id of the implementation>/exec", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
The javascript code was generated from the postman itself, so there should be no differences.
This is the console output:
Also tried axios. Similar issue, but the error was different: Network Error.
I have no idea what to do or where to look. I googled for several hours but nothing I found helped. If anyone have an idea what could be the reason, I would be super grateful.
From Then tried sending post request through postman to the generated url and it worked flawlesly., I confirmed that your Web Apps can be correctly used. In this case, in the case of your script, how about the following modification?
Modified script:
function sendForm() {
var raw = JSON.stringify({"test": "testing from vue"});
var requestOptions = {
method: 'POST',
body: raw,
};
fetch("https://script.google.com/macros/s/<id of the implementation>/exec", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
When I tested this modified script using your Web Apps script, I confirmed that {test=testing from vue} is put to the cell.

Getting 401 Error code while using fetch() with a custom header

===
I've built a custom API with AWS API Gateway.
For one of the method, I've enable the authorization to be checked using a Lambda function.
In order to make it work, I have to add the following key: Key: authorizationToken Value: allow.
I've tested it using Postman and it's working fine, my POST is processed and I receive a response.
I'm just starting with Javascript so I've used the code provided in Postman.
Here it is:
function getData(event){
var myHeaders = new Headers();
myHeaders.set("authorizationToken", "allow");
var requestOptions = {
method: 'POST',
mode: 'no-cors'
};
fetch("https://[THE_URL_OF_MY_API]/prod/counter", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
And i'm getting the following error message in the console.
script.js:49 POST https://[THE_URL_OF_MY_API]/prod/counter
net::ERR_ABORTED 401 (Unauthorized)
getData # script.js:49
I've looked into the logs of the API Gateway in AWS in order to troubleshoot it:
But I can't see any logs so it seems my fetch is being block before
it's even being sent.
I checked the headers of the successful API call sent by Postman and I can't find any header apart from mine and the one generated by the application automatically.
What am I doing wrong ?
Note: I'm using similar code to another endpoint where the authorization is not enabled and it's working fine. SO I guess my header is not correctly set.
Thanks !
#CRice, Salmin Skenderovic, Jaromanda X : Thanks a lot for your feedback.
The missing myHeaders was a typo, I fixed it.
Seeing the comment about the 'no-cors', I've looked into it, enable CORS, authorized my specific header in Access-Control-Allow-Headers.
And now it's working fine.
My amended code:
var myHeaders = new Headers();
myHeaders.set("authorizationToken", "allow");
var requestOptions = {
method: 'POST',
redirect: 'follow',
headers : myHeaders
};
fetch("https://[URL_OF_MY_API_ENDPOINT]/prod/counter", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Configuration of my API Gateway:
Configuration of my API Gateway

Categories

Resources