【问题标题】:How can i test from mocha/superagent a CORS upload call to amazon-s3?如何从 mocha/superagent 测试对 amazon-s3 的 CORS 上传调用?
【发布时间】:2014-02-23 04:46:48
【问题描述】:

我在尝试从 superagent 向 Amazon S3 发出 CORS 请求以上传文件时遇到问题。首先,我向 node.js 服务器询问该策略。我返回一个这样的 JSON 对象:

{
    s3PolicyBase64: '',
    s3Signature: '',
    s3Key: '',
    s3ObjectKey: 'ftriana3185/inputData/input_fdc2f7f4b050c5884e5ac60a43bfc0d8ff26d549.csv' }

然后我尝试从 superagent 使用节点返回的策略来上传本地文件。我的代码如下所示:

it('GET /inputFiles/s3Credential', function(done) {
    var csvPath = './files/inputFileResource/countrylist.csv';
    var request = {};
    request.ext = 'csv';

    clientAgent.get(localPath + '/inputFiles/s3Credential').send(request).end(function(response) {
        var s3PolicyBase64 = response.body.s3PolicyBase64;
        var s3Signature = response.body.s3Signature;
        var s3Key = response.body.s3Key;
        var s3ObjectKey = response.body.s3ObjectKey;

        var request = clientAgent.post('bucket-name.s3.amazonaws.com')
            .type('form')
            .field('key', s3ObjectKey)
            .field('AWSAccessKeyId', s3Key)
            .field('acl', 'public-read')
            .field('policy', s3PolicyBase64)
            .field('signature', s3Signature)
            .attach('mycsv', csvPath).end(function(response){
                console.log(response);
            });
    });
});

我确信问题在于我正在执行来自 superagent 的请求,因为我也有一个可以正常工作的 html 表单。那么,为此目的使用 superagent 的正确形式是什么?

【问题讨论】:

    标签: node.js amazon-s3 cors mocha.js superagent


    【解决方案1】:

    我今天尝试这样做,但发现 HTTP 400 失败。我猜 superagent 不遵守http://aws.amazon.com/articles/1434 中描述的精确表单布局。

    我建议您改用“表单数据”模块 (https://github.com/felixge/node-form-data)。

    这对我有用:

    var FormData = require('form-data');
    var fs = require('fs');
    
    ...
    
    it('should upload to S3 with a multipart form', function (done) {
        var policy = {/* your S3 policy */};
        var form = new FormData();
        form.append('AWSAccessKeyId', policy.AWSAccessKeyId);
        form.append('key', policy.key);
        form.append('policy', policy.policy);
        form.append('signature', policy.signature);
        form.append('file', fs.createReadStream('path/to/file'));
        form.submit('https://YOUR_BUCKET.s3.amazonaws.com/', function (err, res) {
            if (err) return done(err);
            res.statusCode.should.be.exactly(204);
            done();
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-10
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      • 2021-09-19
      • 2015-03-09
      • 2013-10-08
      相关资源
      最近更新 更多