microsoftgraph / msgraph-sdk-javascript Goto Github PK
View Code? Open in Web Editor NEWMicrosoft Graph client library for JavaScript
Home Page: https://graph.microsoft.com
License: MIT License
Microsoft Graph client library for JavaScript
Home Page: https://graph.microsoft.com
License: MIT License
Hi ,
I have a use case where in I need to use a service / background process to get the files present in one drive at an enterprise level . Can you guys please let me know the steps involved.
For getting access token I assume there must be a way with out involving user (such as using a service account etc).
Thanks,
Arvindan
Upgrading the msgraph-sdk-javascript package to 1.2.0 results in a no longer working pnp js search parsing.
Downgrading to version 1.0.0 makes it work again.
With version 1.2.0 of this sdk, I get errors like 'TypeError: Cannot read property 'isUrlAbsolute' of undefined' or 'unexpected token in json at position 0' as result of doing a SharePoint Search via PnP JS. Tested with 1.1.2, 1.1.4 and 1.2.1 of pnp js.
Hello. I was able to successfully replicate the Browser Sample to download my img file. However, when the Sample is adjusted to get a fileitem, the response is an attempted 302 redirect which fails due to CORS policy (per the error message). Given that the URL for the download shouldn't require authorization, this is surprising.
call:
client
.api('/drive/items/' + FileId + '/content')
.responseType('blob')
.get((err, res, rawResponse) => {
if (err) {
console.log(err);
return;
}
console.log(res);
});
Response:
XMLHttpRequest cannot load https://graph.microsoft.com/v1.0/drive/items/01YBCTP6ZQ/content. Redirect from 'https://graph.microsoft.com/v1.0/drive/items/01YBCTP6ZQ/content' to 'https://anonymized.sharepoint.com/_layouts/15/download.aspx?guestaccess…iration=2016-12-05T17%3a23%3a21.000Z&userid=30&authurl=True&NeverAuth=True' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.
Am I missing something, or does the API not support downloading FileItems?
Thanks.
Hello all,
What if we wanted to add some custom data to a Planner Task object for example. The MSGraph does not have that. How can we have this javascript library call a custom WEB API instead, and it can call the MSGraph endpoint instead, and we can add/remove anything as needed? Best way to get/create this WEB API layer that passes the call through and to inject additional properties? Use of swagger would be nice too. thx
After installing the SDK via NPM into a Node.js web app, when I run the app from the command line I get:
Error: Cannot find module 'es6-promise'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Users\jasonjoh\Source\Repos\node.js\node-tutorial\node_modules\@microsoft\microsoft-graph-client\lib\src\GraphRequest.js:5:21)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Users\jasonjoh\Source\Repos\node.js\node-tutorial\node_modules\@microsoft\microsoft-graph-client\lib\src\index.js:4:22)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.9.5
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] start: `node index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script 'node index.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the node-tutorial package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node index.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs node-tutorial
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls node-tutorial
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! C:\Users\jasonjoh\Source\Repos\node.js\node-tutorial\npm-debug.log
Installing es6-promise
manually via npm fixes this. However, you should have this listed as a dependency in your package.json. It's currently only listed under devDependencies
.
After installing this package with npm install @microsoft/microsoft-graph-client
when I run npm start
it shows error message Cannot find module '@microsoft/microsoft-graph-client'
.
Then I tried to check the package status by running command npm outdated
but it shows the package is missing with below detail.
@microsoft/microsoft-graph-client MISSING 1.1.0 1.1.0 node-tutorial
I have downloaded and installed "npm install" . How do i run the sample code ?
Can I do incremental Auth with this library? For example, a user signs in only with the profile but later authorizes access to to their email account or calendar.
Hello,
*.d.ts files in this package contains a reference to:
/// <reference path="../../typings/index.d.ts" />
which is missing after installing package.
using: "msgraph-sdk-javascript": "^0.2.2"
am i missing something? tried to use the microsoftgraph/msgraph-typescript-typings but unfortunately it doesn't support @types yet...
Thanks!
I have tried using the page.contentUrl to return the page content using the client get command and the getStream to no avail. I would appear the get command the result is undefined while the getstream just produces an empty file when trying to write the stream to file.
When I try to run
GET https://graph.microsoft.com/beta/reports/getEmailActivityCounts(period='D7')
Graph Explorer shows an broken image (it returns csv file, so might because not support render csv file)
Same post, postman can show the result:
Report Refresh Date,Send,Receive,Read,Report Date,Report Period
2018-02-26,,1,,2018-02-26,7
2018-02-26,,,,2018-02-25,7
2018-02-26,,2,,2018-02-24,7
2018-02-26,,,,2018-02-23,7
2018-02-26,,,,2018-02-22,7
2018-02-26,,1,,2018-02-21,7
2018-02-26,,1,,2018-02-20,7
AB#6000
hi,
when i send a request to download a file :GET /me/drive/items/{item-id}/content
it will get an error :Request header field SdkVersion is not allowed by Access-Control-Allow-Headers in preflight response.
in request header:
SdkVersion:graph-js-1.2.0
Steps:
The subject is the same as the old one. If you request it again, the update comes through. It seems to be caching? I tried getting around this by adding a nonce to the query string but I got a 400 bad request when doing so.
Is there any support for configuring proxy settings on this library?
Maybe a newbie error but as of 2018-01-14 the package seems to be missing from npm and yarn both?
Complete log:
npm install @microsoft/microsoft-graph-client
npm ERR! code E404
npm ERR! 404 Not Found: @microsoft/microsoft-graph-client@^1.0.0
I have React app and I'm using msgraph-sdk-javascript to connect with Microsoft Graph API. I saw that response with content type - image/jpeg returns null value, so I can not decode the image and share in the app.
Sample query: '/me/contacts/' + id + '/photo/$value'
using [microsoft-graph-client] npm in typescript file like so...
import * as MsGraph from '@microsoft/microsoft-graph-client';
...
let graphClient: MsGraph.Client = MsGraph.Client.init({ authProvider: (done) => { done(null, graphToken); } });
I receive a lot of warnings from web-pack when compiling...
/node_modules/@microsoft/microsoft-graph-client/lib/src/GraphRequest.js
(Emitted value instead of an instance of Error) Cannot find source file '../../src/GraphRequest.ts': Error: Can't resolve '../../src/GraphRequest.ts' in 'C:\Work_projects\JavaScript_react\framework-demo\node_modules@microsoft\microsoft-graph-client\lib\src'
./node_modules/@microsoft/microsoft-graph-client/lib/src/ResponseHandler.js
(Emitted value instead of an instance of Error) Cannot find source file '../../src/ResponseHandler.ts': Error: Can't resolve '../../src/ResponseHandler.ts' in 'C:\Work_projects\JavaScript_react\framework-demo\node_modules@microsoft\microsoft-graph-client\lib\src'
./node_modules/@microsoft/microsoft-graph-client/lib/src/common.js
(Emitted value instead of an instance of Error) Cannot find source file '../../src/common.ts': Error: Can't resolve '../../src/common.ts' in 'C:\Work_projects\JavaScript_react\framework-demo\node_modules@microsoft\microsoft-graph-client\lib\src'
./node_modules/@microsoft/microsoft-graph-client/lib/src/index.js
(Emitted value instead of an instance of Error) Cannot find source file '../../src/index.ts': Error: Can't resolve '../../src/index.ts' in 'C:\Work_projects\JavaScript_react\framework-demo\node_modules@microsoft\microsoft-graph-client\lib\src'
There are no actual errors but I'm wondering if there is something missing
Can we get CDN link for this library? We want to access graph using this library from ScriptLab (https://github.com/OfficeDev/script-lab) but we need JavaScript CDN to do that. ScriptLab does not support TypeScript
In the examples for uploading (.put), you make use of fs.createReadStream, which is specific to Node and not available in the browser. I've tried everything I can come up with to pass in a local file, including all options of FileReader. But all result in the error stream.pipe is not a function. My searching has just about lead me to believe it is impossible to create a readable stream from the browser. But I just can't believe there's no way to upload via the js SDK from the browser? Am I missing something obvious?
If it can be done, an example would be most useful. (I can attest that there is not one anywhere on the entirety of the internet.)
Has anyone been able to use this Vue.js? I would like to use this to get outlook mail.
nextLink
does not work with /delta
for /users/**
. The first request (first page) works fine, but as soon as we want to load more data via nextLink, we get the following error message:
{ code:'SyncStateNotFound', message:'The sync state root folder is not found.' }
Hi, do you plan to release a Java SDK ?
If so, when ? Thanks
GraphRequest.js depends on the ability to open ../../package.json. This breaks the ability to package the script easily with tools like webpack or host the scripts on a CDN, and takes an external dependency on the packaging of the scripts (NPM).
I should clarify that it can be made to work with webpack, but it requires the use of json-loader.
Hello 👋 !
It looks to me like there is no way to access the value provided by the server for Retry-After
when throttling is applied.
It would be good to make it available on the GraphErr
type, but I don't know if you'd want to add it as a top-level property on the object (probably not!) or access to the raw/parsed headers in general.
Let me know what you think!
When trying to use the "Promise" syntax of the .getStream
method (ie. with no callback),
client.api(url).getStream()
.then(stream => {
// do something with stream
})
.catch(err => {
// do domething with err
})
I get the following error:
TypeError: Cannot read property 'then' of undefined
Nevertheless, the"callback" syntax works great:
return new Promise((resolve, reject) => {
client.api(url).getStream((err, stream) => {
if (err) {
// do domething with err
}
else {
// do something with stream
}
});
});
After having retrieved a list of pages I am attempting to get the content of that page. I am using, the response does not include the content, this can be reproduced as follows
getGraphClient().api('/me/onenote/pages/' + entry.pageId + '/content')
.get((err, res, raw) => {
if (err) {
console.log("ERROR: Error retrieving body for page with id " + entry.pageId);
console.log(err)
entry.body = err.message;
} else {
console.log(res)
console.log(raw.res.text);
}
});)
console.log(res)
displays '{}'
WORKAROUND: console.log(raw.res.text)
provides the page content.
I am trying to load the SDK into a Angular2/Typescript application that is using SystemJS. I started with the code from the typescript sample.
import { Client as GraphClient } from "msgraph-sdk-javascript";
Works in the typescript file using the library but I get a 404: cannot access localhost:8080/msgraph-sdk-javscript. If I add this map to my systemjs.config.js:
'msgraph-sdk-javascript': 'node_modules/msgraph-sdk-javascript',
Then I get a 503 unauthorized on the node_modules/msgraph-sdk-javascript directory (why it is trying to access the directory directly is unknown to me). I have also tried aliasing the map to "msgraph" and then adding a package to systemjs.config.js
msgraph: {
main: 'lib/graph-js-sdk-web.js',
defaultExtension: 'js'
},
But that seems to mess up all of the other relative paths loaded by the library itself. How can this library be loaded into such an application?
Like office-js and office-js-helpers, would be cool.
I've been trying to use the following code:
let token = await getAccessToken(authData),
auth_data = token.token,
isRefresh = token.isRefresh;
if (auth_data.access_token) {
const client = graph.Client.init({
authProvider: (done) => {
done(null, auth_data.access_token);
}
});
let url = 'https://outlook.office.com/api/v2.0/me/calendars/${id.id}/events'
const result = await client
.api(url)
.post(event, (err, res) => {
console.log(res);
return cb(res)
})
} else {
return null;
}
To create events i am trying something like above, some of the events created. for some events, it showing like below, it stops the process.
C:\project\node_modules\@microsoft\microsoft-graph-client\lib\src\ResponseHandler.js:48
requestId: errObj.innerError["request-id"],
^
TypeError: Cannot read property 'request-id' of undefined
at Function.ResponseHandler.ParseError (C:\project\node_modules\@microsoft\microsoft-graph-client\lib\src\ResponseHandler.js:48:41)
at Function.ResponseHandler.init (C:\project\node_modules\@microsoft\microsoft-graph-client\lib\src\ResponseHandler.js:14:42)
at C:\project\node_modules\@microsoft\microsoft-graph-client\lib\src\GraphRequest.js:191:55
at Request.callback (C:\project\node_modules\superagent\lib\node\index.js:728:3)
at parser (C:\project\node_modules\superagent\lib\node\index.js:916:18)
at IncomingMessage.res.on (C:\project\node_modules\superagent\lib\node\parsers\json.js:19:7)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1056:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
I don't even understand, why its keeps coming. I can't debug myself, because i newbie in this.
Can you please help me out in this ?
Not sure this is the right github to report this issue. Using https://graph.microsoft.com/v1.0/drives I can see the libraries in my root site collection, name.sharepoint.com/. However I can't seem to find libraries in my other site collections, like name.sharepoint.com/sites/lozzi. Is there a config for it or is this a bug?
It seems that the Extensions field (in my case, Calendar API) is not selectable. The queries were built with /delta. I have seen the following issue: https://stackoverflow.com/questions/47385272/failed-to-get-open-extension-when-use-delta. However, this applies to $expand and filter.
It would be very desirable, otherwise we cannot load custom fields.
Example:
.select("subject,extensions")
I need to set timezone in headers.If i use either header or headers it returns client.header is not a function or client.header is not a function.How and where to set headers
We are not able to find here or online about how reorder buckets/tasks for the Planner. Is there a library/helper that can help with that and should it be in this sdk? thanks!
Hello,
I am trying to access skills for a particular user which can be retrieved from https://graph.microsoft.com/beta/me/skills
(tested at https://developer.microsoft.com/en-us/graph/graph-explorer)
However, when I write a function in my react app for the same:
getSkills(callback) { this.client .api('/me/skills') .get((err, res) => { if (!err) { callback(null, res); } else this._handleError(err); }); }
the response is always 403 (Forbidden). I have updated the application and delegated permissions and have logged in as a user.
I am able to run simple GET requests like https://graph.microsoft.com/beta/me
or GET /users
etc.
Is there something else that needs to be done to enable access to additional endpoints?
Thanks,
Abhi
Due to what I believe is a bug here:
msgraph-sdk-javascript/src/GraphRequest.ts
Line 306 in b3f2309
A getStream call will never return err as non-null. I'm seeing a 401 authorization error and I'm unable to catch it to refresh my token since err is always null. The result is that I end up streaming the JSON error instead of the file I want to retrieve.
client
.api(`/me/drive/items/${args.fileId}/content`) // path of source file in OneDrive
.getStream((err, downloadStream) => {
//err is null even with a bad token
});
Hi, I'm working under corporate proxy. It is not allowing Client to request microsoftGraph.Client.init(). Can anyone please suggest me where to add my proxy and port.
var microsoftGraph = require("microsoft/microsoft-graph-client");
var token=;
var client = microsoftGraph.Client.init({
authProvider: (done) => {
// Just return the token
done(null, token);
}
});
Our testing experience has shown that intermittently the MSGraph can fail.
In our test-suite we've extended the time out of Mocha and this has resolved it, but we cannot do this in the main code as timeout property/method of superagent
is not exposed.
Would it be possible to expose it as an option with a default perhaps?
Hi Dan,
in version 0.3.0, there's an build error due to the assignments:
common.d.ts:
export declare const DEFAULT_VERSION = "v1.0";
export declare const GRAPH_BASE_URL = "https://graph.microsoft.com/";
i'd love to start working with this library :-)
Itay
When uploading an image as a stream from node app, it results in Error: read ECONNRESET, so not able to upload image more than 120KB
Hello
This just a question.
How i can check for outdated token and implement update of token?
Error TS2307: Cannot find module '@microsoft/microsoft-graph-client'.
The same happens, when trying to import @microsoft/microsoft-graph-types. Oddly, VS Code resolves the path to the module correctly, but gulp throws the above mentioned error while building.
2123487
I've been trying to use the following code:
client
.api('/planner/tasks/' + task.id)
.header("If-Match", task["@odata.etag"])
.patch(patchString).then(function (res) {
// refresh the data
loadContextData();
$("#pivotContainer").find("*").prop('disabled', false);
$('#spinnerLoading').css({ "display": "none" });
showNotification('Success!', 'Update the new task');
}).catch(function (err) {
// catch any error that happened so far
console.log("Error: " + err.message);
});
To update a Planner task. In Graph Explorer the basic REST call with all the same parameters returned status 204 and the task was updated. In my code using the Graph SDK js, the status 204 came back but the task was not updated.
I found that the Content-Type used by the SDK patch call was "application/x-www-form-urlencoded" and not "application/json" like the Graph Explorer and as I would expect.
I added:
.header("Content-Type", "application/json")
and the task was updated as expected.
Is this a bug in Graph SDK js patch() call? Should "application/json" be the default header used or is it more common to use this other Content-Type?
Hey there,
Thanks for open-sourcing this library!
It'd be great if someone updated the Readme to address pagination.
For example, accessing a user's contacts with an MS Graph query to /contacts
returns 10 results per page by default. It's possible to add a $top
query parameter to increase that page size.
However, it should definitely be mentioned that the result["@odata.nextLink"]
URL (returned with the query response) needs to be queried in order to get the rest of the user's contacts (as well as all additional result["@odata.nextLink"]
s!).
I know it's basic pagination 101, but this library's documentation should really include an overview of paging.
I need to call Graph API through a corporate proxy, but I found no mean to pass options to the underlying fetch() library, in order to specify the proxy URL or a custom HTTP(S) agent.
I think it would be great to provide a way to pass options to fetch(), so it will solve any issue about proxy, timeout or any environment-specific needs.
I'm trying to copy a page from one section to another as documented.
Code to do the move:
getGraphClient().api('/me/onenote/pages/' + entry.pageId + '/copyToSection')
.post({"id": newSection.id},
(err, res) => {
if (!err) {
console.log("Moved entry to '" + entry.status + "'");
} else {
console.log(err);
}
});
When this is run I get a 501 status code with message "OData Feature not implemented. {0}"
There is every chance I am doing something stupid since in the Graph Explorer using:
and post body:
{"id": "0-d66b9407FB17D322!OBFUSCATED"}
I get:
{
"error": {
"code": "20111",
"message": "OData Feature not implemented. {0}.",
"innerError": {
"request-id": "d672b0e0-1de8-4565-8cd1-9163d8854c6b",
"date": "2017-11-11T09:16:28"
}
}
}
Naturally I have done my best to verify that the ids are correct etc. I'm convinced they are as I can create a new page with the same content then delete the original page using the same ID's as those used in the failed copy. This is not satisfactory as my create time is now incorrect.
client
.api('/me/drive/root/children')
.get((err, res) => {
console.log(res);
});
This is returning null in value
response.
I have given all the delegated and application permissions in my app.
Still not able to access the children from my OneDrive.
Trying to query my calendar and return the next 5 events.
Query setup:
client
.api('/me/events')
.header('X-AnchorMailbox', email)
.top(5)
.filter('Start/DateTime ge 2017-05-26T00:00:00')
.select('subject,start,end')
.orderby('start/dateTime DESC')
When executed Graph replies with:
"code":"BadRequest","message":"The DateTimeOffset text '2017-05-26T00:00:00.000' should be in format 'yyyy-mm-ddThh:mm:ss('.'s+)?(zzzzzz)?' and each field value is within valid range."
Does 2017-05-26T00:00:00
not match 'yyyy-mm-ddThh:mm:ss('.'s+)?(zzzzzz)?'
?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.