App Engine Cloud Endpoint Javascript library does not work - javascript

I tried to enable Cloud Endpoint via this document.
After defining the API and doing some configuration, finally the API can be viewed and executed via API Explorer successfully.
However, I cannot enable the Javascript client to run:
<html>
<script type="text/javascript">
function init() {
var ROOT = "https://my-app-id.appspot.com/_ah/api";
gapi.client.load('my-app-id', 'v1', function() {
gapi.client.bigquery.query({
'start_date': '2013-05-01',
'end_date': '2013-05-02',
'metrics': ['impr']
}).execute(function(resp) {
console.log(resp);
});
}, ROOT);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
</html>
I noticed the request failed during the Javascript execution, but I cannot figure out why.
Request
https://my-app-id.appspot.com/_ah/api/discovery/v1/apis/my-app-id/v1/rpc?
Response
{"error":{"errors":[{"domain":"global","reason":"notFound","message":"Not Found"}],"code":404,"message":"Not Found"}}

Use your API name, not my-app-id. Also, make sure your API is deployed and serving. If not, this would similarly cause a 404.
See google cloud endpoints discrepancy between documentation, and what works in my app for an identical question.

Related

Accessing a Web API from JavaScript after being authenticated against Azure AD B2C

I am developing a .Net Web App where after authenticating against Azure AD B2C through the Azure AD Connect protocol the controller in my app gets an access token through the MSAL library (C# code) to access a backed Web API. That works all fine.
Now from the same web app I need to use JavaScript to access the same backed Web API. My question is how can I leverage the access token obtained through my server side C# code to get my client side JavaScript to access the Web API without being prompted to sign-in.
I used the sample code on GitHub to get me started.
Below is my JavaScript code. When I run it I get the following error "user_login_error:User login is required"
if (!clientApplication) {
clientApplication = new Msal.UserAgentApplication(window.config.clientID, window.config.authority, authCallback);
clientApplication.redirectUri = window.config.redirectUri;
}
function ReloadInfo(type, language, location) {
clientApplication.acquireTokenSilent(window.config.b2cScopes).then(function (accessToken) {
ReadResource(accessToken, type, language, location);
}, function (error) {
clientApplication.acquireTokenPopup(window.config.b2cScopes).then(function (accessToken) {
ReadResource(accessToken, type, language, location);
}, function (error) {
debugger
logMessage("Error acquiring the access token to call the Web api:\n" + error);
});
})
}
Thanks!
A simple solution for this scenario is that you can create a corresponding controller to call the web API.
And in the JavaScript, you can call your web app instead of the web API directly. Since you have sign-in, the JavaScript can call the controller successfully. And in this sencario, there is no need to use MSAL library for JavaScript.
Update
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
$("#Location").change(function () {
$.ajax({
url: "data.html",//modify the path HTTP request you wanted
}).done(function (data) {
console.log(data);// handle the result data here
});
});
})
</script>
You can refer here about full jQuery document.

authenticating a service account to call a Google API with JavaScript client library

I want to make JSON-RPC calls from localhost (WAMP environment) to the Google FusionTables API (and a couple of other APIs) using the Google Client Library for JavaScript
Steps I have taken:
setup a project on the Google Developer Console
enabled the FusionTables API
created a service account and downloaded the JSON file.
successfully loaded the JS client library with the auth package: gapi.load('client:auth2', initAuth);
constructed the init method parameter the following 3 ways:
the downloaded JSON verbatim
the downloaded JSON modified to include the scope
just the client ID and scope
tried (and failed) to initialize the GoogleAuth instance: gapi.auth2.init(params)
function failed(reason) {
console.log(reason);
}
gapi.load('client:auth2', initAuth);
function initAuth() {
var APIkey = 'MY API KEY';
gapi.client.setApiKey(APIkey); //I understand this to be unnecessary with authorized requests, included just for good measure
var GDTSAKey = 'MY SERVICE ACCOUNT KEY';
var scopes = 'https://www.googleapis.com/auth/fusiontables';
gapi.auth2.init({
client_id: "101397488004556049686",
scope: 'https://www.googleapis.com/auth/fusiontables'
}).then(signin, failed("couldn't initiate"));
//passing the downlaoded JSON object verbatim as parameter to init didn't work either
} //initAuth()
function signin() {
gapi.auth2.getAuthInstance().signIn().then(makeAPIcall), failed("couldn't sign-in");
}
function makeAPIcall(){
gapi.client.load('fusiontables', 'v2', function(){
var tableId = '1PSI_...';
var table = gapi.client.fusiontables.table.get(tableId);
document.querySelector("#result").innerHTML = table;
});
}
based on JS client library >> Samples
the gapi.auth2.init method invokes the second callback (which I understand to be an error handler): failed("couldn't initiate"), but then, curiously, I also get `couldn't sign in' which could only have originated from within the provided success handler. What's going on? How do I get this to work?
Note: I am only willing to try the CORS/xhr, if there is no way to do it with JS client lib.
What's going on?
You are trying to use a service account with the Google JavaScript client library which does not support service accounts.
How do I get this to work?
Switch to Oauth2 authentication or if you must use a service account switch to a server sided language like PHP or python for example. Which support service account authentication.

signalR connection failing when trying to connect with cross domain hosted signalr service

I am trying to consume signalR on a website. SignalR is a self hosted service.
SignalR url: http://localhost8080:/signalr
Website is running # http://localhost:31775/
I am getting error on browser console
GET
http://localhost:31775/signalr/negotiate?connectionData=%5B%5D&clientProtocol=1.3&_=1442784297380
404 (Not Found)
This error tells me that proxy that the code below is trying to generate is using website url i.e. relative path. However I want to use absolute path where my signalR service is hosted.
AngularJS Factory
app.factory("signalRService", ['$', '$rootScope', function ($, $rootScope) {
var proxy;
var connection;
return {
connect: function () {
connection = $.hubConnection();
proxy = connection.createHubProxy('myHub');
connection.start();
proxy.on('addMessage', function (tags) {
$rootScope.$broadcast('addMessage', tags);
});
},
send: function () {
proxy.invoke('send');
},
};
}]);
I also added javascript reference for this.
<script src="js/jquery.signalR-2.0.3.min.js"></script>
To validate if my self hosting is running file. I checked http://localhost:8080/signalr/hub on browser
What you are missing is a bit of configuration of the proxy:
connection = $.hubConnection('http://localhost:8080/signalr');
How to generalize on that piece of code (the url could be an argument of your connect method, or whatever fits your Angular strategy) is up to you.

Uncaught ReferenceError: init is not defined

im a newbie in javascript and wanted to learn something, I've been wondering, i found this on https://developers.google.com/api-client-library/javascript/features/cors where i can use cors so i can access a google API like kissflow, i dont know if im in the right way. so here's the thing, im using the standalone Auth client that was described in the said site, but everytime i tried to run the program the error prompt
Uncaught ReferenceError: init is not defined
i just copied the code at the site which is
<script src="https://apis.google.com/js/api.js"
type="text/javascript">
</script>`<script type="text/javascript">`
//<![CDATA[gapi.load('auth', init);//]]>
</script>
Try this:
<script src="https://apis.google.com/js/api.js"
type="text/javascript">
</script>
<script>
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "<YOUR_CLIENT_ID>"});
});
</script>
Make sure that you host this locally, and when creating the client ID, add the localhost URL with the port. Without a URL, the client ID will not send back a proper response, resulting in an error. Since the client ID doesn't support "file:///", you have to use a web hosting service or something, or the easier route, just download the latest python and set up a localhost server.
Latest python download: https://www.python.org/downloads/
Setting up the server: https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server#running_a_simple_local_http_server
Note that sometimes you have to use "py" instead of "python" for reasons I am too lazy to research 😊.
To actually initiate the login and use the API:
<script>
function authenticate() {
return gapi.auth2.getAuthInstance().signIn({scope: ""/*Declare scopes with spaces in between, depends on API you're using*/})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("<YOUR_API_KEY>");
return gapi.client.load(""/*Declare discovery document, depends on API you're using*/)
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
function execute() {
return gapi.client.classroom.courses.list({}) //Used classroom courses list as an example, but use the apropriate API Fields, found in your method's "Overview" section on the API Documentation
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "<YOUR_CLIENT_ID>"});
});
authenticate().then(loadClient).then(execute)
</script>
Note that sometimes you have to clear cache in order for this to work (I mean, worked for me), so if you have some trouble, try that.

Google API in Javascript

I am trying to get calendar info from google in javascript. I ve read 'how to' manuals. They didn't help. Even this 'helpful' copypasted code (to authorize) didn't. Would somebody be so kind to teach me how to use google api? Maybe someone has some samples to share
And this beautiful js code :
<html>
<button id="authorize-button" onclick='handleAuthClick()'>Authorize</button>
<script type="text/javascript">
var clientId = '***';
var apiKey = '***';
var scopes = 'https://www.googleapis.com/auth/plus.me';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
// Step 3: get authorization to use private data
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
// Step 4: Load the Google+ API
gapi.client.load('plus', 'v1', function() {
// Step 5: Assemble the API request
var request = gapi.client.plus.people.get({
'userId': 'me'
});
// Step 6: Execute the API request
request.execute(function(resp) {
var heading = document.createElement('h4');
var image = document.createElement('img');
image.src = resp.image.url;
heading.appendChild(image);
heading.appendChild(document.createTextNode(resp.displayName));
document.getElementById('content').appendChild(heading);
});
});
}
</script>
Error Message (from Console):
'Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').'
so im stuck on 'gapi.auth.authorize'. nothing works after
Based on the error you're receiving, my guess is that you either do not have your Javascript Origin configured properly on the Google API console you got your Client ID from, and/or you are trying to run your script from the file system instead of through a web server, even one running on localhost. The Google API client, near as I've been able to tell, does not accept authorization requests from the file system or any domain that has not been configured to request authorization under the supplied Client ID.
Google API Console reference :
In Client ID for web application:
Javascript Origins : http://localhost:3000/
Key for browser applications:
Referers : http://localhost:3000/
localhost would work 100%
i got the same error and as you preferred, after running html file in my local web server problem solved.
i created credentials for web application and set following values both to my local with "http://localhost:5000" string
"Authorized JavaScript origins"
"Authorized redirect URIs
i checked the json file too. i got the following json file as a result.
{"web":
{
"client_id":"myClientID",
"project_id":"my-project",
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
"client_secret":"XqXmgQGrst4xkZ2pgJh3Omxg",
"redirect_uris":["http://localhost:5000"],
"javascript_origins":["http://localhost:5000"]
}
}
https://developers.google.com/drive/v2/web/auth/web-client
Some APIs will work fine when queried from local files, but some won't.
In response to an error such as yours, try to serve your files from a web server. If you need a quick web server running, use Python's builtin HTTP server (Mac OSX and Linux systems have Python pre-installed). This HTTP server can turn any directory in your system into your web server directory. cd into your project directory and run the following command:
python -m SimpleHTTPServer 3000 The number at the end is the port number your http server will start in and you can change that port number. In our example, your directory would be served from: http://localhost:3000.

Categories

Resources