生成每个请求的S3 Put URL

时间:2015-10-13 19:34:21

标签: node.js amazon-s3

如何根据NodeJS的每个请求生成预先签名的S3 URL?我存储多个存储桶的存储桶名称,区域,IAM用户密钥和IAM用户密码。不幸的是,我发现的所有示例都显示AWS配置正在全局更新:

我发现的所有示例都显示以下config.*行让我害怕:

var AWS = require('aws-sdk');

AWS.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY});
AWS.config.region = 'eu-west-1';

此代码似乎全局设置配置...这将破坏可能同时发生的每个后续请求或请求。

我想从存储的IAM凭据和存储桶名称动态加载所有内容,并使用存储的信息生成URL:

var aws     = require('aws-sdk'),
    express = require('express'),
    Repo    = require('../../models');

function createUrl (req, res, next) {

    var endpointId  = (req.params.endpointId || '').toUpperCase(),
        fileType    = req.body.type || '',
        fileName    = req.body.name || '',
        fileSize    = req.body.size || '';

    Repo.Endpoints.findById(endpointId, function (err, item) {
        if (err) { return next(err); }
        if (!item) { return next(new Error('Unknown endpoint')); }

        var config = {
            accessKeyId     : item.iamUserAccessKey,
            secretAccessKey : item.iamUserSecret,
            region          : item.bucketRegion
        };

        var params = {
            Bucket      : item.bucketName,
            Key         : fileName,
            ContentType : fileType
        };

        var s3 = new aws.S3(config);
        s3.getSignedUrl('putObject', params, function(err, url) {
            if(err) console.log(err);
            res.send({ url: url });
        });
    });
}

然而,这段代码感觉不对......就像我错过了一些关键的东西。

更新10/13/2015 19:33 EST
但是生成了URL,当我尝试执行POST时出现错误:

XMLHttpRequest cannot load https://<%URL FROM SERVER%>. No 'Access-Control
-Allow-Origin' header is present on the requested resource. Origin 'http:
//localhost:4003' is therefore not allowed access. The response had HTTP 
status code 403.

斗上的CORS政策是:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
    <CORSRule>
        <AllowedOrigin>http://localhost:4003</AllowedOrigin>
        <AllowedOrigin>http://lvh.me:4003</AllowedOrigin>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <ExposeHeader>x-amz-server-side-encryption</ExposeHeader>
        <ExposeHeader>x-amz-request-id</ExposeHeader>
        <ExposeHeader>x-amz-id-2</ExposeHeader>
        <AllowedHeader>Authorization</AllowedHeader>
        <AllowedHeader>Origin</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

0 个答案:

没有答案