Node JS promise request for PUT with auth

I want to upload a file to the server with a promise request.

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') }
      ]
    };

The constructor function has:

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);
  });

I never succeed or catch a mistake. What should be wrong? The actual work that needs to be done is curl:

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

What is the best approach for this? Can a promise request do this?

+4
source share
1 answer

Got it for download with changing parameters:

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

Is there a better approach?

+4
source

Source: https://habr.com/ru/post/1648358/


All Articles