I have been working on Hyperledger composer for my project. I am trying to build a multi user web app. But I can't however, call the REST method POST /wallet/{name}/setDefault.
I used the code below to do a POST request but it returns an error "Unhandled error for request POST /api/wallet/admin%40sample/setDefault: Error: Authorization Required"
function myLogin(){
var id = document.getElementById("bId").value;
var signIn = id + "#sample";
var xhr = new XMLHttpRequest();
var url = "http://localhost:3000/api/wallet/" + id + "%40sample/setDefault";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var obj ={
"name": signIn
}
var data = JSON.stringify(obj);
xhr.send(data);
console.log(url);
}
I have used Github oauth and had already given authorization to each and every participant in the network. But still, it shows the Error.
Related
I have client - server express app. Im trying to send an XHR request from frontend to my controller, while passing json data. My frontend code looks like this:
function handle_login(){
var username_field = document.getElementById('input_username');
var pass = document.getElementById('input_password');
if(username_field.value!=null)console.log(username_field.value);
console.log(pass.value);
//window.location.href = "/loginAttempt/"+username.value+"-"+pass.value;
var xhr = new XMLHttpRequest();
var url = "/home_pogled";
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-type", "application/json");
var data = {
username : username_field.value,
password : pass.value
}
var json = JSON.stringify(data);
xhr.send(json);
xhr.onload = function() {//ob uspesnem odgovoru
var responseText = xhr.responseText;
//console.log("Backend server response -" +responseText);
// uporabi odgovor
};
xhr.onerror = function() {
console.log('There was an error!');
};
}
I can send the request and i'm certain that data is written to the json object prior to sending it, but when i do consonle.log(req.body) in my controller upor receiving the request the body is empty "{}", where is should havec ontained the username and password values in a json objkect. What am i missing?
Client Side:
We can't send object in GET method, it should be query params like below snippet
let url = `/home_pogled?username=${username_field.value}&password=${pass.value}`;
xhr.open('GET', url);
Server side (express app):
In express js, we can get the query params in req.query
let username = req.query.username;
let password = req.query.password
I am getting the raw data of the drafted from Gmail API "get" method and sending it using Gmail API "send" method.
'var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/id?
format=raw&alt=json&access_token=' + token;
url = url.replace("id", emailId);
var x = new XMLHttpRequest();
x.open('GET', url , true);
x.send();
x.onload = function() {
var jsonRes = JSON.parse(x.response);
sendEmail(jsonRes.raw);
}
function sendEmail(raw) {
if (raw) {
var request = new XMLHttpRequest();
var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json&access_token=' + token;
params = "raw=" + raw;
request.open('POST', url , true);
request.setRequestHeader("Authorization", "Bearer " + token);
request.setRequestHeader("Content-type", "application/json");
request.send(params);
request.onload = function() {
if (200 === request.status) {
alert("Email sent successfully");
}
}
}`
I am getting 401 status.
If I am sending this raw data from API page itself, then it is sent successfully. Therefore the raw data is correct.
I am missing something while sending the email. Please help!
A 401 error means "invalid credentials", most likely because your token has expired or isn't valid.
The Google API explorer and Google Javascript libraries take care of the token for you (generally), but if you're calling the service endpoints directly with XMLHttpRequest(), you'll have to manage the token yourself.
If you want to go that route, here are the details you have to implement: https://developers.google.com/identity/protocols/OAuth2
You can try things out in the "Oauth2 playground": https://developers.google.com/oauthplayground/
Thank you for all responses.
I sent the email using the following code-
function sendEmail(raw) {
if (raw) {
var request = new XMLHttpRequest();
var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/send';
var params = JSON.stringify({'raw': raw});
request.open('POST', url , true);
request.setRequestHeader("Authorization", "Bearer " + token);
request.setRequestHeader("Content-type", "application/json");
request.send(params);
request.onload = function() {
if (200 === request.status) {
alert("Email sent successfully");
}
}
}
}
There were two mistakes I rectified-
1. The token was sent in URL as well as header. It should be sent only in header.
2. The param raw was sent as String but it should be sent as a JSON object.
I want the poster of required movie from TMDB. I am not able to get JSON data from TMDB API. I have send the request but getting error 404 'The resource you requested could not be found'.
Link to access TMDB movie API : https://developers.themoviedb.org/3/movies/get-movie-images
Here is my code:
<script type="text/javascript">
var film = "speed";
var api_key = 'my-api-key';
var requestURL = "https://api.themoviedb.org/3/movie/images?api_key=" + api_key +"&language=en-US&callback=?";
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function(){
var myjsondata = request.response; //request.response contains all our JSON data
console.log(myjsondata);
}
</script>
The JSON data in my console should look like this:
But instead I am getting this in my console:error 404 This resource cannot be found.
You need to include a movie_id value in the path part of the request URL, right? Like this:
var requestURL = "https://api.themoviedb.org/3/movie/"
+ movie_id + "/images?api_key=" + api_key +"&language=en-US&callback=?";
At least in the documentation cited in the question that’s what’s shown:
GET /movie/{movie_id}/images
Path Parameters
movie_id : integer
Example:
https://api.themoviedb.org/3/movie/{movie_id}/images?api_key=<<api_key>>
For example, to get JSON-formatted data for the images for the movie with the ID 9340:
https://api.themoviedb.org/3/movie/9340/images?api_key=<<api_key>>
You can confirm that works by testing with curl or whatever:
$ curl "https://api.themoviedb.org/3/movie/9340/images?api_key=<<api_key>>"
{
"backdrops": [
{
"aspect_ratio": 1.777251184834123,
"file_path": "/qKeyO9gXaaK0g87tvvqOPK1siwc.jpg",
"height": 1688,
"iso_639_1": null,
"vote_average": 5.454545454545455,
"vote_count": 3,
"width": 3000
},
…
I'm trying to add a user who clicks on a button in a SharePoint (online) site to a Office 365 group. I know this can be done via JSON using the Add Member API.
https://github.com/OfficeDev/microsoft-graph-docs/blob/master/api-reference/v1.0/api/group_post_members.md
I am however really inexperienced when it comes to JSON and keep messing up the POST function. This is the code I have currently, everything before the comma has been working fine.
function showButton() {
$('btn-1').on('click', function(event) {
var userProfileProperties
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
userProfileProperties = peopleManager.getMyProperties();
clientContext.load(userProfileProperties);
clientContext.executeQueryAsync(onSuccess, onFail);
function onSuccess(){
accountProperties = userProfileProperties.get_userProfileProperties();
accountId = accountProperties['msOnline-ObjectId'];
//JSON Query
jQuery.ajax({
url: "https://mysite.sharepoint.com/groups/groupID/members/$ref";
method: "POST";
contentType: "application/json";
dataType: 'json',
{
"#odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/" + accountId
};
});
};
function onFail(){
alert(failed);
};
});
};
In your document , you will find authentication token is required in the Request headers .Without authentication token ,you will receive an error as :
"code": "InvalidAuthenticationToken", "message": "Bearer access token is empty."
As a solution , you could try following steps :
1.Register a javascript Application in Azure AD and configure your app to allow the OAuth 2.0 implicit grant flow.Tokens are obtained using the OAuth 2.0 implicit grant flow. Using implicit grant, your application requests an access token from Azure AD for the currently signed-in user by sending the user to an authorization URL where the user signs in with their Office 365 credentials and then is redirected back to the app with the access token in the URL .
2.Add permissions to Graph API .
3.Add an html page to your sharepoint online(using Explorer mode) .
4.Edit the html , write below function to get an access token:
function requestToken() {
// Change clientId and replyUrl to reflect your app's values
// found on the Configure tab in the Azure Management Portal.
// Also change {your_subdomain} to your subdomain for both endpointUrl and resource.
var clientId = '3dadb44e-feaa-4158-90f5-e129e15db66d';//ID of your App in Azure
var replyUrl = 'https://o365e3w15.sharepoint.com/sites/XXX/app.html'; //my sharepoint page that requests
//an oauth 2 authentification and data
//It is also referenced in the REPLY URL field of my App in Azure
var endpointUrl = 'https://graph.microsoft.com/v1.0/me/messages';
var resource = "https://graph.microsoft.com/";
var authServer = 'https://login.windows.net/common/oauth2/authorize?';
//var authServer = 'https://login.microsoftonline.com/common/oauth2/authorize?';//this works either
var responseType = 'token';
var url = authServer +
"response_type=" + encodeURI(responseType) + "&" +
"client_id=" + encodeURI(clientId) + "&" +
"resource=" + encodeURI(resource) + "&" +
"redirect_uri=" + encodeURI(replyUrl);
window.location = url;
}
After that ,you could make an ajax call to graph api endpoint to get/post request, for example, get current user's messages:
var endpointUrl = "https://graph.microsoft.com/v1.0/me/messages";
var xhr = new XMLHttpRequest();
xhr.open("GET", endpointUrl);
var myToken = getToken();
// The APIs require an OAuth access token in the Authorization header, formatted like this:
//'Authorization: Bearer <token>'.
xhr.setRequestHeader("Authorization", "Bearer " + myToken);
// Process the response from the API.
xhr.onload = function () {
if (xhr.status == 200) {
//alert('data received');
var message="";
var object = JSON.parse(xhr.response);
for(i=0;i<object.value.length;i++){
message+='Subject: ' + object.value[i].subject + '<br>';
}
document.getElementById("results").innerHTML = message;
} else { }
}
// Make request.
xhr.send();
display this app.html into any SharePoint Webpart page by calling it within an iframe tag.
All detail steps you will find in this article , i have tested and work fine in my side .
I was making a automation script to extract some info from a website, And It's important to submit some info using POST method. Can anyone tell me how to use HTTP Post method with Imacro & javascript for firefox plugin. Below is the script which i found here : Sending an HTTP Post using Javascript triggered event
But it's giving me error when i play the same using Imacro player.
var url = "http://www.google.com/";
var method = "POST";
var postData = "Some data";
var async = true;
var request = new XMLHttpRequest();
request.onload = function () {
var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
var data = request.responseText; // Returned data, e.g., an HTML document.
}
request.open(method, url, async);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.send(postData);
XMLHttpRequest() is no longer supported in firefox 15+
You have to define it:
const XMLHttpRequest = Components.Constructor("#mozilla.org/xmlextras/xmlhttprequest;1");
var request = XMLHttpRequest();
To run JavaScript in iMacros you can use this method.
URL GOTO=javascript:window.ScrollTo(0,150);
Try this method.
In your case it would look like this.
URL GOTO=javascript:var url = "http://www.google.com/";var method = "POST";var postData = "Some data";var async = true;var request = new XMLHttpRequest();request.onload = function () var status = request.status; var data = request.responseText; request.open(method, url, async);request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");request.send(postData);