经过一段时间的研究,我终于学会了如何使用oAuth2并使用刷新令牌创建访问令牌。但是我找不到关于上传文件的node.js示例,我只找到了这个模块https://www.npmjs.com/package/onedrive-api。
请问您能否发送一份使用node.js上传文件到OneDrive API的示例代码?非常感谢。
备注:我也尝试过使用以下代码上传文件。
同样的代码:'未认证' 的东西 :/
但是这对我没有用,因为我收到了这个错误{error:{code:'未验证',message:'身份验证失败'}}
即使我手动输入accessToken:'xxxxxxx'结果也是相同的。但是在上传之前,我已经创建了访问令牌,所以我不知道这是否真的会成为无效的信用问题。但有趣的是,如果我从https://dev.onedrive.com/auth/msa_oauth.htm获取access token(您可以生成1小时的access token),上传功能将正常工作。 我根据这个问题的回答创建了我的授权。OneDrive Code Flow Public clients can't send a client secret - Node.js
另外,我只使用了Files.readWrite.all范围,我可能需要允许其他某些范围吗? 我的代码是:
const oneDriveAPI = require('onedrive-api');
const onedrive_json_configFile = fs.readFileSync('./config/onedrive.json', 'utf8');
const onedrive_json_config = JSON.parse(onedrive_json_configFile);
const onedrive_refresh_token = onedrive_json_config.refresh_token
const onedrive_client_secret = onedrive_json_config.client_secret
const onedrive_client_id = onedrive_json_config.client_id
// use the refresh token to create access token
request.post({
url:'https://login.microsoftonline.com/common/oauth2/v2.0/token',
form: {
redirect_uri: 'http://localhost/dashboard',
client_id: onedrive_client_id,
client_secret: onedrive_client_secret,
refresh_token: onedrive_refresh_token,
grant_type: 'refresh_token'
}
}, function(err,httpResponse,body){
if (err) {
console.log('err: ' + err)
}else{
console.log('body full: ' + body)
var temp = body.toString()
temp = temp.match(/["]access[_]token["][:]["](.*?)["]/gmi)
//console.log('temp1: ', temp)
temp = temp.join("")
temp = temp.replace('"access_token":"','')
temp = temp.replace('"','')
temp = temp.replace('\n','')
temp = temp.replace('\r','')
//console.log('temp4: ', temp)
oneDriveAPI.items.uploadSimple({
accessToken: temp,
filename: 'box.zip',
parentPath: 'test',
readableStream: fs.createReadStream('C:\\Exports\\box.zip')
})
.then((item,body) => {
console.log('item file upload OneDrive: ', item);
console.log('body file upload OneDrive: ', body);
// returns body of https://dev.onedrive.com/items/upload_put.htm#response
})
.catch((err) => {
console.log('Error while uploading File to OneDrive: ', err);
});
} // else from if (err) { from request.post
}); // request.post({ get access token with refresh token
请问您能否发送一份使用node.js上传文件到OneDrive API的示例代码?非常感谢。
备注:我也尝试过使用以下代码上传文件。
var uri = 'https://api.onedrive.com/v1.0/drive/root:/' + 'C:/files/file.zip' + ':/content'
var options = {
method: 'PUT',
uri: uri,
headers: {
Authorization: "Bearer " + accesstoken
},
json: true
};
request(options, function (err, res, body){
if (err) {
console.log('#4224 err:', err)
}
console.log('#4224 body:', body)
});
同样的代码:'未认证' 的东西 :/
refresh_token
?我在Azure应用程序中找不到它。在Azure应用程序中,我只能看到client_id
和client_secret
。 - Saurabh Chauhan