tsuda7 tsuda7 - 2 months ago 8
HTTP Question

http module (of node.js with browserify) doesn't write request body with method PATCH

I've been developing a web client to interact with a REST API server, and would like to use PATCH method.

Although I've tried to write a request body into PATCH's request, I found the body remains empty. PUT or POST works fine in the same way though.

I can use PUT instead, but does anyone know if my usage of http module is wrong?

Thank you in advance.

var http = require('http');

module.exports = {

patch: function(path, data, done, fail){
var jsonData = JSON.stringify(data);
var options = {
headers: {
'Content-Type':'application/json;charset=UTF-8',
'Content-Length':jsonData.length,
}
};
var req = this.request(path, "PATCH", done, fail, options);

// THIS CODE DOESN'T WRITE jsonData INTO REQUEST BODY
req.write(jsonData);
req.end();
},

request: function(path, method, done = () => {}, fail = () => {}, options = { headers: {} } ){
options.path = path;
options.method = method;
return http.request(options, function(res){
var body = '';
res.setEncoding('utf8');
res.on("data", function(chunk){
body += chunk;
});
res.on("end", function(){
// process after receiving data from server
});
}).on("error", function(e) {
// process after receiving error
});
}
}

Answer

I ended up using the "request" library for node.js. Following code works:

var request = require("request");
(...)

function patch(path, entity){
    var deferred = q.defer();     
    var escapedPath = escapeSpaces(path);
    AuthProvider.retrieveToken().done(function (authToken){
        var headers ={
            'OData-MaxVersion': '4.0',
            'OData-Version': '4.0',
            'Content-Type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer '+ authToken,
            'Accept': 'application/json'     
        }

        var options = {
            url: "https://"+resourceApiId+"/api/data/v8.0/"+escapedPath,
            method: 'PATCH',
            headers: {
                'OData-MaxVersion': '4.0',
                "OData-Version": '4.0',
                "Content-Type": "application/json; charset=utf-8",
                "Authorization": 'Bearer '+ authToken,
                "Accept": "application/json"                
            },
            json: entity      
        };  

        request(options, function(error, response, body){
                if (!error) {
                    console.log("patchrequest statuscode: "+response.statusCode )
                    deferred.resolve(true);
                }
                deferred.reject(error);
            }
        );
    });

    return deferred.promise;
}