My goal is to create a folder programmatically in OneDrive API using Javascript/Jquery in the application that I'm building. I am not using Node.js or Angular.js. I have registered my application with OneDrive's Application Registration Portal, then used the token flow to get the access token from my web browser url address bar. Now that I have the access token, I'm trying to send it and my request to the API. Below is my code:
var accesshash = window.location.hash.substring(1);
//console.log(url);
console.log(accesshash);
var token = JSON.parse('{' + accesshash.replace(/([^=]+)=([^&]+)&?/g, '"$1":"$2",').slice(0,-1) + '}', function(key, value) { return key === "" ? value : decodeURIComponent(value); });
console.log(token.access_token);
var url = "https://graph.microsoft.com/v1.0/me/drive/root/children/"
var xhr = new XMLHttpRequest();
if(xhr.readyState == 4) {
console.log("success");
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer " + token.access_token);
var newfolder = {
"name": "0000000000",
"folder": {}
}
xhr.send(newfolder);
I'm getting this as my JSON response:
{
"error": {
"code": "BadRequest",
"message": "Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.",
"innerError": {
"request-id": "c8d43cbc-a59b-4244-8c4e-9193295ec7f8",
"date": "2018-06-07T19:42:57"
}
}
}
Does this mean that my access token is at least valid? Or is something wrong with it? Is there something I'm missing? This is my first time attempting to integrate Onedrive API into an application.
You are sending object, but content type is application/json, json is string representation of javascript object
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8"); // added charset
xhr.setRequestHeader("Authorization", "Bearer " + token.access_token);
var newfolder = {
"name": "0000000000",
"folder": {}
}
xhr.send(JSON.stringify(newfolder)); // converted to string
There are many http libraries like fetch, request - that can make your life much easier
Related
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.
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
},
…
A simple guide to making a GET request to get a user's messages through Gmail API can be found here.
But the way we are instructed to do the request is in the following manner:
function getMessage(userId, messageId, callback) {
var request = gapi.client.gmail.users.messages.get({
'userId': userId,
'id': messageId
});
request.execute(callback);
}
Is it possible to make the request using the good ol' XMLHttpRequest object on the client side? If so what parameters should be passed into the call?
I have tried this:
var getMessages = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200)
console.log(xhr.responseText);
}
xhr.open( "GET", "https://www.googleapis.com/gmail/v1/users/me/messages", true );
xhr.send();
}
But I get a 401, even after authenticating.
As it states in this answer, you should pass the access token as a query parameter with the name access_token, or prefix the authorization header value with "Bearer", like so:
xhr.setRequestHeader("authorization", "Bearer " + userToken.access_token);
I'm uploading files to a GCS bucket with the JSON API and the upload is resumable. I'm doing this from the browser using JS.
The files upload with no problems. If there is a network problem then I try to resume it. Per the documentation I'm sending an empty PUT request to the upload URI. Then parsing the range header of the response. But then I get the error:
Refused to get unsafe header "range"
This is the code:
var xhr = new XMLHttpRequest();
xhr.open("PUT", url, true);
xhr.setRequestHeader("Authorization", token);
xhr.setRequestHeader("content-range", "bytes */" + file_object.size);
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) {
return;
}
if (xhr.status === 308) {
var range = xhr.getResponseHeader("range"); // Error here
// continue with the upload
}
};
xhr.send();
I'm creating the upload URI at the server side with Python. These are the headers included in the request:
headers = {
"Authorization": authorization,
"Content-Type": "application/json; charset=UTF-8",
"origin": 'http://' + self.request.headers.get('HOST'),
"X-Upload-Content-Type": content_type,
"X-Upload-Content-Length": content_length,
}
How can I read the header range?