这里是后端代码,id和key都是根账号的
var LongBucketName = config.Bucket;
var ShortBucketName = LongBucketName.substr(0, LongBucketName.indexOf('-'));
var AppId = LongBucketName.substr(LongBucketName.indexOf('-') + 1);
console.log(ShortBucketName, AppId)
// 实例配置
var policy = {
'version': '2.0',
'statement': [{
'action': [
"name/cos:PutObject",
"name/cos:GetObject",
"name/cos:DeleteObject",
"name/cos:GetBucket",
"name/cos:HeadBucket",
"name/cos:GetBucketCORS",
'name/cos:PostObject',
// 分片上传
'name/cos:InitiateMultipartUpload',
'name/cos:ListMultipartUploads',
'name/cos:ListParts',
'name/cos:UploadPart',
'name/cos:CompleteMultipartUpload'
],
'effect': 'allow',
'resource': [
'qcs::cos:' + config.region + ':uid/' + AppId + ':prefix//' + AppId + '/' + ShortBucketName + '/这里是更账号/*',
],
}],
}
module.exports = {
getAuthorization: function() {
return new Promise((resolve, reject) => {
const StartTime = Number(JSON.stringify(new Date().getTime()).slice(0, 10))
STS.getCredential({
secretId: config.SecretId,
secretKey: config.SecretKey,
region: config.Region,
policy: policy,
durationSeconds: 7200
}, function (err, data) {
if (err) {
reject(err)
} else {
var credentials = data.credentials
resolve({
TmpSecretId: credentials.tmpSecretId,
TmpSecretKey: credentials.tmpSecretKey,
XCosSecurityToken: credentials.sessionToken,
ExpiredTime: data.expiredTime,
StartTime
})
}
})
})
}
}
这里是前端代码
const GetAuthorization = (options, callback) => {
const url = 'http://127.0.0.1:3001/getAuthorizationInqCloud' // 如果是 npm run sts.js 起的 nodejs server,使用这个
const xhr = new XMLHttpRequest()
let credentials = null
xhr.open('POST', url, true)
xhr.onload = function (e) {
try {
credentials = JSON.parse(e.target.responseText)
} catch (e) {
console.error('error:'+ e)
}
console.log(credentials, credentials.TmpSecretId, 'options')
callback({
TmpSecretId: credentials.TmpSecretId,
TmpSecretKey: credentials.TmpSecretKey,
XCosSecurityToken: credentials.XCosSecurityToken,
StartTime: credentials.StartTime, // 密钥申请时服务器时间
ExpiredTime: credentials.ExpiredTime // SDK 在 ExpiredTime 时间前,不会再次调用 getAuthorization
})
}
xhr.send()
}
let cos = new COS({
getAuthorization: GetAuthorization
})
const headBucket = () => {
cos.headBucket({
Bucket: config.Bucket,
Region: config.Region
}, function(err, data) {
console.log(err || data, cos)
// if (err) {
// console.log(err)
// console.log(err.error);
// }
})
}
module.exports = {
headBucket
}
打印出的错误是
相似问题