The request sent by jQuery or JavaScript doesn't contain the Header so I received error 405 - header

I have the HTML file and try to send the request from that page with JavaScript or jQuery, but it doesn't send the "header" to the server and it gives me the error 405. I've read related questions and try out some of them but the error code was the same. I use Fiddler to see the final request and in that there is no header as well as the method change to the OPTION!
some of the codes I used:
$.ajax({
url: "URL",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer HASHKEY');},
success: function() { alert('Success!'); }
});
or
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "URL", true);
xhttp.setRequestHeader("Authorization", "Bearer HASHKEY");
xhttp.setRequestHeader('Content-Type', 'text/plain');
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.send();
xhttp.onreadystatechange = function () {
var response = xhttp.responseText;
if (xhttp.readyState == 4 && xhttp.readyState == 200) {
var obj = JSON.parse(response);
// handle data as needed...
alert("obj" +obj);
}
};
Totally speaking I'm looking for a piece of code which can call API from the HTML which is content header: authorization.
Cheers

Try this:
$.ajax({
url: "URL",
type: "GET",
‎headers: {
‎"Authorization": "Bearer HASHKEY"
‎},
success: function() { alert('Success!'); }
});
Also, check that your server configuration supports CORS and explicitly allows the Authorization header.

Related

Getting error while framing request URL using appscript

I am trying to frame request for API using appscript.
var url_string = "https://*.cognitiveservices.azure.com/vision/v3.2/describe"
let body = {
'"url"':'"https://www.khwaahish.com/wp-content/uploads/2022/01/khwaahish-white-bg-logo.jpg"'
};
const headers = {
'method' : 'POST',
'Host':'imagealttextcreation.cognitiveservices.azure.com',
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key':'###',
'payload': body
};
var response = UrlFetchApp.fetch(url_string,headers)
Logger.log(response)
I am getting invalid request error. But the same thing is working when i try manually(attached image for same).
Am I missing something while forming this request in the appscript?
When tried manually using the browser the functionality works. i want help in correcting the request using appscript.
From the official document, in your script, how about the following modification?
Modified script:
var url_string = "https://*.cognitiveservices.azure.com/vision/v3.2/describe";
let body = { url: "https://www.khwaahish.com/wp-content/uploads/2022/01/khwaahish-white-bg-logo.jpg" };
const options = {
headers: { "Ocp-Apim-Subscription-Key": "###" }, // Please set your value.
payload: JSON.stringify(body),
contentType: "application/json"
};
var response = UrlFetchApp.fetch(url_string, options);
Logger.log(response.getContentText())
Reference:
fetch(url, params)

How do I resolve the CORS error in Yelp API call?

I'm trying to call the Yelp Fusion API using AJAX but I'm getting the following error below. Could someone help me figure out what's going on here?
api.yelp.com/v3/:1 Failed to load resource: the server responded with a status of 403 ()
index.html:1 Access to XMLHttpRequest at 'https://api.yelp.com/v3/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here's the code I'm using:
var queryURL = "https://api.yelp.com/v3/";
var apiKey = "my key"
$.ajax({
url: queryURL,
method: "GET",
headers: {
"accept": "application/json",
"Access-Control-Allow-Origin":"*",
"Authorization": `Bearer ${apiKey}`
}
}).then(function(res) {
var results = res.data
console.log(results);
});
Try using the CORSAnywhere proxy, plug your key in the snip below and give it a shot:
// JavaScript Document
var queryURL = "https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/";
var apiKey = "my key";
$.ajax({
url: queryURL,
method: "GET",
headers: {
"accept": "application/json",
"x-requested-with": "xmlhttprequest",
"Access-Control-Allow-Origin":"*",
"Authorization": `Bearer ${apiKey}`
},
success: function(result){
console.log(result);
}
});

Amazon Gateway API with Lambda - Could not parse request body into json

I seem to be getting a issue with Amazon Gateway API not liking my sent params for example.
$.ajax({
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
type: "POST",
data: {
"device": "test",
"datetime": "1446757400919"
},
success: function (returnhtml) {
console.log(returnhtml);
$("#result").append("DOES NOT WORK - <br>" + JSON.stringify(returnhtml));
}
});
$.ajax({
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
type: "POST",
data: {},
success: function (returnhtml) {
console.log(returnhtml);
$("#result").append("<br>WORKS ???? - <br>" + JSON.stringify(returnhtml));
}
});
Here is a working example.
http://jsfiddle.net/Uwcuz/4315/
Can someone let me know why it wont let me send params every time i add a parameter i get this error.
{
Type = User;
message = "Could not parse request body into json.";
}
OK THIS WORKS BUT SEEMS A BIT WEIRD TO ME.
$.ajax({
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
type: "POST",
data: "{\"device\": \"test\",\"datetime\": \"1446757444524\"}",
success: function (returnhtml) {
console.log(returnhtml);
$("#result").append("WORKS - <br>" + JSON.stringify(returnhtml));
}
});
The problem lies in how you send the data to API Gateway.
Without knowing the details of your API configuration I am guessing that you have a Request Mapping setup for application/json.
jQuery will by default post your data as application/x-www-form-urlencoded but you want to send it as json.
You can do this without having to fiddle too much with the data yourself:
var requestParams = {
url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
method: "POST,
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
"device": "test",
"datetime": "1446757400919"
});
};
var request = $.ajax(requestParams);
The key here is JSON.stringify() and telling jQuery that the dataType is json as well as setting the contentType to application/json.

500 error on UrlFetchApp

I am trying to pass data of a product list from Magento API to Google Spreadsheet.
No authentication was required for the Magento API as I was retrieving the data as a Guest. The API is working perfectly with RestClient.
However, 500 error occurred when fetching the REST resource from Googe Apps Script.
Exception: Request failed for
http://mymagentohost/api/rest/products?limit=2
returned code 500. Truncated server response: Service temporary
unavailable (use muteHttpExceptions option to examine full response)
This is my Google Apps Script:
function myscript() {
var url = "http://mymagentohost/api/rest/products?limit=2"
var response = UrlFetchApp.fetch(url);
var out = JSON.parse(response.getContentText());
var doc = SpreadsheetApp.create("Product Info");
var cell = doc.getRange('a1');
var index = 0;
for (var i in out) {
var value = out[i];
cell.offset(index, 0).setValue(i);
cell.offset(index, 1).setValue(value);
index++;
}
Any ideas?
Hey the trick is to add the following headers to your request
var url = "http://mymagentohost/api/rest/products?limit=2"
var params = {
headers: { 'Content-Type': "application/json", 'Accept': "application/json"},
muteHttpExceptions: true,
method: "GET",
contentType: "application/json",
validateHttpsCertificates: false,
};
var response = UrlFetchApp.fetch(url, params);
Believe the key params for Magento not to return 500 "Service temporary unavailable" are the Content-Type and Accept headers but all params mentioned in example are useful, YMMV.

Same Origin Policy Error when using jQuery JSONP with CloudFlare API

I recieve an error (XMLHttpRequest cannot load https:// www.cloudflare.com/api_json.html?tkn=&email=&z=&a=rec_load_all&callback=%3F. Origin http:// domainmanager.tech-bytes.org is not allowed by Access-Control-Allow-Origin.) (spaces inserted in URLs due to Stack Overflow link limit) when trying to send a JSONP request via jQuery to CloudFlare. The CloudFlare API states that you can ask for a JSONP callback by appending a &callback=mycallback parameter. I am not sure if I am supposed to replace mycallback with something, I tried replacing it with ? as that is what some other resources said, or if I have to do some other modifications to my code.
Try in this way for cross domain request.
$.ajax({ url: "yourUrl",
data:{paramName1: JSON.stringify(paramValue1),paramName2: JSON.stringify(paramValue2)},
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(data) {
alert(data.d);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
You can use CORS for this purpose.
Example code:
jQuery.support.cors = true;
function CrosDom_ajax(url) {
if (window.XDomainRequest
&& $.browser.msie
&& $.browser.version < 10) {
xdr = new XDomainRequest();
if (xdr) {
xdr.onload = function () {
alert(xdr.responseText);
};
xdr.open("get", url);
xdr.send();
}
}
else {
$.ajax({
url: url,
success: function (response) {
},
error: function (data) {
}
});
}
}
Also you need to Write the following code in server side, to allow cross domain access
Response.AppendHeader("Access-Control-Allow-Origin", "*");