Search code examples
node.jsrequesthttp-postpromisehttp-put

How to properly use putAsync after promisify request module


I searched here and there and ended up with no finding regarding putAsync method of promisified request by bluebird.

var request = require('request');
var Promise = require('bluebird');
Promise.promisifyAll(require("request"));

request.putAsync({
    uri: buApiUrl,
    headers: {
        'content-type': 'application/json'
    },
    body: JSON.stringify({
        name: BU,
        workstations: formattedWorkStaions[BU]
    })
}).spread(function (response, body) {
    debugHelper.log(body);
}).catch(function (err) {
    debugHelper.error(err);
});

Above is the code snippet that is in my program. And it does not send put request. While using postAsync, if will send post request successfully.

Can anyone help explain why?


Solution

  • I already found the part where is wrong in the putAsync code snippet. I should use json not body as the key for the payload. And the payload does not need to be stringified. Here is the new code snippet proven to work.

    var request = require('request');
    var Promise = require('bluebird');
    Promise.promisifyAll(require("request"));
    
    request.putAsync({
        uri: buApiUrl,
        headers: {
            'content-type': 'application/json'
        },
        json: {
            name: BU,
            workstations: formattedWorkStaions[BU]
        }
    }).spread(function (response, body) {
        debugHelper.log(body);
    }).catch(function (err) {
        debugHelper.error(err);
    });

    This is quite tricky and result in my second question. Why there is such a difference between post and put other than their method type?