How to send body through xmlhttprequest for a POST request? - javascript

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.

Related

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.

How to disable SSL certificate verification while post request in react JS?

I am trying to use keycloack for user authentication,
I need to disable SSL verification for some testing purpose.
In postman it works well if I disable SSL certificate verification.
But in my react JS code it is giving me and error (net::ERR_CERT_AUTHORITY_INVALID) even it is disabled as shown in below code.
Kindly correct me if anything missing in the below code or any else need to do.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("grant_type", "password");
urlencoded.append("client_id", "clientid");
urlencoded.append("username", "username");
urlencoded.append("password", "password");
urlencoded.append("client_secret", "clientsecret");
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow',
Agent: httpsAgent
};
fetch("serverurl/realms/realmname/protocol/openid-connect/token", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
ERROR: net::ERR_CERT_AUTHORITY_INVALID
As I got a workaround,
Just enter the request URL in the browser and if getting trust error, just click on Advanced and go with unsafe to load the request, it may required at least 3 attempts to do the same then page will load.
and try the same request through react app then it will not give you such SSL error.

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

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.

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

Getting error 415 - Unsupported media Type in fetch api

Following curl request is working and it's generating token. But when I use it as fetch API, I'm getting 415 error - Unsupported media type.
curl -k -X POST -H "Content-Type: application/x-www-form-urlencoded" -u "Secret_ID:Secret_Key" -d "grant_type=password&username=mahesh#gmail.com&password=Welcome1234&scope=https://si01-test.prod.com/bca/api" "https://identity.com/oauth2/v1/token"
I'm using fetch API like this:
let username = 'Secret_ID';
let password = 'Secret_Key';
let formdata = new FormData();
let headers = new Headers();
formdata.append('Content-Type','application/x-www-form-urlencoded');
formdata.append('grant_type','password');
formdata.append('username','mahesh#gmail.com');
formdata.append('password','Welcome1234');
formdata.append('scope','https://si01-test.prod.com/bca/api');
headers.append('Authorization', 'Basic VGVzdF9zaTAxX0FQUElEOjNkZGI4MmYxLWI5OTktNDlhMy1hMmM5LWQ1OGMyOTU2ODg4Yg=='); // encoded username and password
fetch('https://identity.com/oauth2/v1/token', {
method: 'POST',
headers: headers,
body: formdata
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
What's wrong here? Any suggestion will be appreciable..
So as I mentioned, Request is working fine in CuRL / Postman and it makes my life easier.
If you you have curl command and its working fine then you can just import that command directly in postman and it will work fine.
Now if your request is working fine in postman, then you can just copy code of it in any language that is given in Postman.

Categories

Resources