===
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
Related
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.
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.
What i try to do
I have a small ReactJS application. In this application, i try to do an REST request to the API of SpreadShirt via the JS Fetch API.
What fails
Basically i get no data. The console of the browser shows the following output:
Access to fetch at 'https://api.spreadshirt.net/api/v1/shops/100749149/sellables?mediaType=json' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
My Code
getData() {
const header = new Headers({
"Authorization": "SprdAuth apiKey=\"XXXXXXXXX"",
"User-Agent": "MukoSoft/1.0 (https://mydomain.de; my#mail.de)"
});
const options = {
method: 'GET',
headers: header
};
fetch('https://api.spreadshirt.net/api/v1/shops/100749149/sellables?mediaType=json', options)
.then(response => response.json())
.then(data => this.setState({ data: data }))
.then(() => this.setState({ loading: false }))
}
Does anyone has a hint for me, while i can't fetch via JavaScript? And can somebody explain, why the request via Postman works, but not via fetch API?
Since this is my first question on stack overflow, you can give me advices on how to formulate questions better
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.
I'm trying to get an OAuth token for the Reddit API following the Application Only OAuth instructions. My reddit app is an installed app, so for my grant_type I'm using https://oauth.reddit.com/grants/installed_client.
Currently I'm running a very short JS script to query the API and get a token:
const APP_ID = 'MY_APP_ID'
const DEVICE_ID = 'TRACKING_ID_20_TO_30_CHARS'
let form = new FormData()
form.append('grant_type', 'https://oauth.reddit.com/grants/installed_client')
form.append('device_id', DEVICE_ID)
fetch('https://www.reddit.com/api/v1/access_token', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${btoa(`${APP_ID}:`)}`,
}),
body: form })
.then(handleResponse)
.then(function(data) {
console.log(data)
})
.catch(error => console.error(error))
function handleResponse(response) {
return response.json()
}
(Note: running the snippet as-is will give you a NetworkError because the APP_ID isn't a real one and I don't want to give mine out.)
The response I get is:
{
"error": "unsupported_grant_type"
}
When I try the same API request using a REST client I get back the expected response, so this makes me think that the problem is JavaScript-related. Since the grant_type matches what the instructions say I'm not really sure what to do with the error. I'm hoping someone else more experienced with OAuth will know what is going on here.
The problem was the use of the FormData object. In earlier stages of troubleshooting I found this answer on Reddit and decided to use it, but that didn't work for me.
It was submitting the data as multipart/form-data rather than application/x-www-form-urlencoded, which Reddit's OAuth server did not like. I wrote a helper function based on this answer which did the trick:
function urlEncode(data) {
let out = [];
for (let key in data) {
out.push(`${key}=${encodeURIComponent(data[key])}`);
}
return out.join('&')
}