Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS request-promise for PUT with auth

I want to upload a file to server with 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') }
      ]
    };

The constroller 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 get to success nor catch an error. What must be wrong? Actual work to be done is a curl like this:

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

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

like image 617
Nisha Avatar asked Jul 19 '16 09:07

Nisha


People also ask

Is request promise deprecated?

This package is also deprecated because it depends on request . Fyi, here is the reasoning of request 's deprecation and a list of alternative libraries.

Does node js support promise?

In Node. js, we can use the util. promisify() utility module to easily transform a standard function that receives a callback into a function that returns a promise.


1 Answers

Got it to upload with change in options:

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

Is there any better approach?

like image 116
Nisha Avatar answered Oct 11 '22 12:10

Nisha