Calling Google Cloud API Gateway from Web(Javascript) - javascript

I am new to this Google Cloud API Gateway. I followed each and every step in the document to create an API Gateway and its a success. I'm using Google API Gateway with differents backends like Google Cloud Function.
https://cloud.google.com/api-gateway/docs/quickstart
I tested this through the curl command and it's working fine - like getting the response from the backend (Cloud functions). Now, I want to do it programmatically. Calling the API Gateway from the website. When I tried to do it, I am getting the error like below
Error:
Access to XMLHttpRequest at 'https://[mygatewayid].uc.gateway.dev/hello2/' from origin 'http://localhost:5000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
POST https://[mygatewayid].uc.gateway.dev/hello2/ net::ERR_FAILED
My API calling from the web
$.ajax({
type: "post",
url: "https://[mygatewayid].uc.gateway.dev/hello2/",
data:{
PhoneNumber: phonum
},
async: true,
cache: false,
success: function(data,status) {
console.log("Data: " + data);
},
error : function(x, e) {
console.log(x.responseText);
}
});
My cloud function
exports.hello2 = functions.https.onRequest((req,res)=>{
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");
var phonum = req.body.PhoneNumber;
console.log("phonum",phonum);
let message = req.query.PhoneNumber || req.body.PhoneNumber || 'Hello World!';
res.status(200).send(message);
});
My API Config file
Am I doing it in the wrong way(Calling)?
Thanks in advance

The feature is not yet available and should arrive soon. For now, you can add an OPTION in your openAPI spec, like that
paths:
"/hello2":
options:
operationId: create-cors
responses:
200:
description: Success
get:
........

Related

Problem calling an API that requires a key in header, using JS and Ajax

Since I want to display the result of an API call in a HTML page, I used Ajax in a Javascript to get the information from the API.
The DEV API does not require a key, and I have been able to get the result (yeah!)
$.ajax({
url: "https://api-dev.XXXXXXXXX.com/enterprise/123456/treeCount/2020-05",
async: false,
success: function(result){
totalCount = totalCount + result.count;
}
}),
So this code above works fine.
The Prod API requires a key in the header though, and I can't make it work. Found lots of example in StackOverflow, but all my tests failed.
$.ajax({
url: "https://api.XXXXXXXXX.com/enterprise/123456/treeCount/2019-12",
headers: { "x-api-key" : "12345678910" },
async: false,
success: function(result){
totalCount = totalCount + result.count;
}
})
It works well in Postman when adding x-api-key with the value of the key, so I know that the key is good
Any idea what I'm doing wrong?
Thanks!
EDIT February 15th:
Thanks for your answers. Went in the console, saw some CORS error, and then I added some information related to CORS and to Content-Type, so my new code in the JavaScript is the following:
$.ajax({
url: "https://api.XXXXXXXXXX.com/enterprise/123456/treeCount/2019-12",
headers: { "x-api-key" : "12345678910",
"Content-Type" : "application/json",
'Access-Control-Allow-Origin': '*' },
async: false,
success: function(result){
totalCount = totalCount + result.count;
}
})
Still get the same error message though:
jquery-3.3.1.min.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
jquery-3.3.1.min.js:2 Access to XMLHttpRequest at 'https://api.XXXXXXXXX.com/enterprise/123456/treeCount/2020-05' 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.
jquery-3.3.1.min.js:2 Failed to load resource: net::ERR_FAILED
When In only do the call on the Dev API (who does not require an API key), it works fine as indicated above, and I do not get the CORS error.
Again, thanks for your help.

CORS Error:Response to preflight request doesn't pass access control check when trying to access Azure Search Api

I am using an ajax put request to perform a merge operation to update a field named DocType for a particular document in azure search index. But getting the error: Failed to load resource: the server responded with a status of 404 (Not Found)
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
The ajax request I am performing:
var jsonMeta = {
"value": [
{
"#search.action": "merge",
"metadata_storage_path": "*******jkio********",
"DocType": "Test_Merge"
}
]
};
var jsonString = JSON.stringify(jsonMeta);
var url = "https://documentsmartdetect.search.windows.net/indexes/document-smartdetect-index/docs/index?api-version=2017-11-11";
$.ajax({
url: url,
method: 'PUT',
data: JSON.stringify(jsonMeta),
// This is the important part
xhrFields: {
withCredentials: true
},
crossDomain: true,
contentType: 'application/json',
headers: {
"api-key": "***************89**",
},
success: function (response) {
},
error: function (xhr, status) {
alert('error');
}
});
I have also tried using Allowed origin type : all on the azure portal. Need some assistance to fix the CORS issue.
Azure Search does not allow calls from front-end JavaScript, so you cannot do what you want directly.
You will have to call Azure Search from a back-end.
This is actually a serious security problem as well since your Search key is now public within the JavaScript that is sent to all visitors of your web app.

Ionic using Bing Maps Proxy failing and Access-Control-Allow-Origin issue

I'm currently working on my first hybrid application and I'm having an issue with CORS. The Bing MAP API doesn't allow localhost or an actual device to call their Rest API. I've tried to reach Bing two different ways.
First attempt was with the url in my service and all urls whitelisted in the config.xml but I reached and error.
Second was to proxy the url, which is a query url. I'm not sure how to proxy a query url so I've been using a reformatted test url, but that keeps getting a 404.
Anyone know how I can fix my CORS issue? Thank you in advance
'Approach 1`
service.js
function getUserAddress() {
var uriQuery = http://dev.virtualearth.net/REST/v1/Locations/point?point=40.444009, -77.774055&includeEntityTypes=Address,Neighborhood,CountryRegion&includeNeighborhood=1&output=json&key=(removed);
return $http({
method: 'GET',
url: uriQuery,
}).then(function (response) {
console.log("location data set", response);
return getNearbyEvents(response);
}).catch(rxEventsService.onRequestFailure);
}
Config.xml
<access origin="*"/>
<allow-navigation href="*"/>
Error in Chrome
XMLHttpRequest cannot load http://dev.virtualearth.net/REST/v1/Locations/point?point=40.444009,-77.77405&include…=json&key=(remove :) ). No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 404.
Approach 2
gulp.js
// webserver: Create local webserver with livereload.
gulp.task('webserver', function () {
gulp.src('./www')
.pipe(webserver({
fallback: './www/index.html',
host: '0.0.0.0',
port: 8080,
proxies: [{
source: '/_bingmaps',
target: 'http://dev.virtualearth.net/REST/v1/Locations/point?point=40.444009, -77.774055&includeEntityTypes=Address,Neighborhood,CountryRegion&includeNeighborhood=1&output=json&key=(removed)'
}]
}));
});
constants.js
(function () {
'use strict';
angular.module('rxEvents').constant('rxUrls', {
reverseGeoCoding:'/_bingmaps',
bingMapsKey:'(removed)'
});
})();
service.js
function getUserAddress() {
return $http({
method: 'GET',
url: rxUrls.reverseGeoCoding,
}).then(function (response) {
console.log("location data set", response);
return getNearbyEvents(response);
}).catch(rxEventsService.onRequestFailure);
}
Error
ionic.bundle.min.js:135 POST http://localhost:8080/_bingmaps 404 (Not Found)
The Bing Maps REST services are JSONP enabled services. Here is a blog post explaining how to access this service using various JavaScript frameworks: https://blogs.bing.com/maps/2015/03/05/accessing-the-bing-maps-rest-services-from-various-javascript-frameworks/

CORS blocks LinkedIn share API

I try to post new content using LinkedIn share API through JavaScript from AngularJS application as given below.
var xml = "<share><comment>" + content + "</comment><visibility><code>anyone</code></visibility></share>";
var req = {
method: 'POST',
url: 'https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=' + account.token,
headers: {
'Content-Type': 'text/plain'
},
data: xml
};
$http(req).success(function(data) {
console.log(data);
console.log('published to linkedin');
}).error(function() {
console.log(arguments);
console.log('failed to publish to linkedin');
});
I can successfully POST this data. However the browser blocks the response from being read because the response doesn't have an 'Access-Control-Allow-Origin' header.
But, I have given the http://localhost:3000 and 'https://localhost:3000' domains in LinkedIn application settings.
And the request/response in Chrome looks like this.
Any thoughts on how to be able to read the response and not let the browser block it?
I think the problem is the missing Access-Control-Allow-Origin header in the LinkedIn API response?
Looks like LinkedIn's REST API doesn't support CORS. They suggest to use REST API from the backend and not from browser. JS-SDK must be used from the browser.
https://developer-programs.linkedin.com/forum/cors

Reddit API /api/morechildren returns "No 'Access-Control-Allow-Origin' header" using mootools

I've tried the following basic Reddit API morechildren request using mootools:
var moreChildren = new Request({
async: true,
url: 'http://www.reddit.com/api/morechildren',
method: 'post',
data: {
api_type: "json",
children: "cl2vjlp",
link_id: "2ijczu",
sort: "top"
},
onSuccess: function(response){
commentData = JSON.parse(response);
console.log(commentData);
}
});
// tried above request with and without the following line
delete moreChildren.headers["X-Requested-With"];
moreChildren.send();
And I'm receiving a XMLHttpRequest cannot load http://www.reddit.com/api/morechildren.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403. in Google Chrome.
Observations:
Adding .json to reddit/api/morechildren(.json) does not resolve
deleting "X-Requested-With" header does not resolve
Any help is greatly appreciated. :)
This is because of same origin policy - CORS.
you do well to remove this:
// tried above request with and without the following line
delete moreChildren.headers["X-Requested-With"];
but if the reddit site does not support it, it won't work.
you have 2 options:
local proxy, ajax call to local, local server-side to reddit, back and output to browser
use JSONP where available.
can't test your case as it needs oauth but via info.json which is GET, you can:
http://jsfiddle.net/dimitar/zy3rwpjs/
new Request.JSONP({
url: 'http://www.reddit.com/api/info.json',
callbackKey: 'jsonp',
data: {
url: 'http://www.reddit.com/buttons'
},
onSuccess: function(response){
console.log(response.data, response.kind);
}
}).send();
obviously, when it expects POST, things get more complex... JSONP works as GET.
if all you care about is your own project and google chrome, you can start with with --disable-web-security flag, which will allow the call.

Categories

Resources