摸着石头过河吧
这里先占个楼,慢慢盖。。。。。
公司业务需要,准备将一些资源放在天翼云对象存储上,于是就有了这个系列的填坑记录
后端是Nodejs Express
AWS SDK S3的安装请参考Get started with Node.js - AWS SDK for JavaScript
一上午的时间大概的看了一下SDK文档,感觉很简单于是入手
结果在new S3Client(config)的时候一直是CredentialsProviderError错误,郁闷了,按理说应该很简单的事,无非就是配置验证信息,折腾了半天才发现accessKeyId,secretAccessKey是credentials部分的内容。完整的config结构应该是
var config = {
credentials: {
accessKeyId: process.env.accessKeyId,
secretAccessKey: process.env.secretAccessKey,
},
region: "cn",
endpoint: process.env.endpoint,
};
好了这样就可以正常对接到天翼云的对象存储了。是不是很简单
然后添加一个响应吧,"/listbuckets"用于读取对象存储上的桶信息
router.get("/listbuckets", async function (req, res, next) {
try {
const client = new S3Client(config);
const input = {};
const command = new ListBucketsCommand(input);
const response = await client.send(command);
console.log(response);
res.json(response.Buckets);
} catch (e) {
console.log(e);
res.json({ errormessage: "读取文件目录失败" });
}
});
再加上读取指定桶的文件列表
router.get("/listobjects", async function (req, res, next) {
try {
const client = new S3Client(config);
const input = { Bucket: req.query.bucket };
const command = new ListObjectsCommand(input);
const response = await client.send(command);
console.log(response);
res.json(response.Contents);
} catch (e) {
console.log(e);
res.json({ errormessage: "读取" + req.query.bucket + "目录文件失败" });
}
});
好了,这下后面的故事就看各自的发挥了