具有auth的PUT的节点JS请求承诺

时间:2016-07-19 09:49:53

标签: node.js curl request promise

我想通过请求承诺将文件上传到服务器。

var requestPromise = require('request-promise');
var options = {
      uri: 'myurl.com/putImage/image.jpg',
      method: 'PUT',
      auth: {
        'user': 'myusername',
        'pass': 'mypassword',
        'sendImmediately': false
      },
      multipart: [
      {
        'content-type': 'application/json',
        body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
      },
      { body: 'I am an attachment' },
      { body: fs.createReadStream('test.jpg') }
      ]
    };

constroller功能有:

requestPromise.put(options)
  .then(function() {
    response = {
      statusCode: 200,
      message: "Success",
    };
    log.info("Success");
    res.status(200).send(response);
  })
  .catch(function (error) {
    response = {
      statusCode: error.status,
      message: error.message
    };
    log.info(response);
    res.status(400).send(response);
  });

我从未获得成功,也没有发现错误。什么一定是错的?要做的实际工作是这样的卷曲:

curl --verbose -u myusername:mypassword -X PUT --upload-file test.jpg myurl.com/putImage/image.jpg

最佳方法是什么?请求承诺可以这样做吗?

1 个答案:

答案 0 :(得分:8)

上传了选项中的更改:

var options = {
      uri: 'myurl.com/putImage/image.jpg',
      method: 'PUT',
      auth: {
        'user': 'myusername',
        'pass': 'mypassword'
      },
      multipart: [
      { body: fs.createReadStream('test.jpg') }
      ]
    };

有没有更好的方法?

相关问题